我正在为多人游戏开发服务器,我想为每个玩家提供自己的 Lua 线程,我想填充一些独特的全局变量,例如玩家的姓名和 ID。基本上,我希望能够从主机应用程序设置线程局部变量,而无需在我正在编写的实际脚本中添加任何额外的代码,然后我可以在播放会话期间使用它,只要我调用一个函数。Lua有可能吗?
// Example of how it naturally doesn't work
var L = Lua.LuaLNewState();
Lua.LuaRegister(L, "print", WriteLine);
dostring(L, "print('hello, world')", null);
var x = Lua.LuaNewThread(L);
Lua.LuaPushLiteral(x, "charId");
Lua.LuaPushNumber(x, 123);
Lua.LuaRawSet(x, Lua.LUA_GLOBALSINDEX);
dostring(x, "print('x1 '..charId)", null); // call to a function that uses charId
var y = Lua.LuaNewThread(L);
Lua.LuaPushLiteral(y, "charId");
Lua.LuaPushNumber(y, 456);
Lua.LuaRawSet(y, Lua.LUA_GLOBALSINDEX);
dostring(y, "print('y1 '..charId)", null); // call to a function that uses charId
dostring(x, "print('x2 '..charId)", null); // I want this to still be 123
更新:我的应用程序是多线程的,多个播放器可以同时运行脚本。我对在 Lua 中设置函数环境的理解是它会全局更改它,这在我的情况下不起作用。