如何在Lua 5.3中的diffent luathreads中获得具有相同函数名的luathread函数? 在5.1工作成功中使用getglobal,但在5.3工作错误下,
此代码是主要运行调用luathread函数
const char * gLua0 = "function Test() print(12) end";
const char * gLua1 = "function Test() print(23) end";
lua_State * sL0 = newLuaThread();
luaL_loadbuffer(sL0, gLua0, strlen(gLua0), nullptr);
lua_State * sL1 = newLuaThread();
luaL_loadbuffer(sL1, gLua1, strlen(gLua1), nullptr);
lua_getglobal(sL0, "Test");
lua_pcall(sL0, 0, 0, 0);
lua_getglobal(sL1, "Test");
lua_pcall(sL1, 0, 0, 0);
// ---- lua 5.1的结果
12
23
// ----- lua 5.3的结果
23
23
为什么结果5.3与5.1不同?
这段代码是在lua 5.1中创建lua线程
lua_State * newLuaThread()
{
lua_State * sL = lua_newthread(L);
lua_pushvalue(L, -1);
int nRef = luaL_ref(L, LUA_REGISTRYINDEX);
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setmetatable(L, -2);
lua_pushvalue(L, LUA_GLOBALSINDEX);
lua_setfield(L, -2, "__index");
lua_setfenv(L, -2);
lua_pop(L, 1);
return sL;
}
这段代码是在lua 5.3中创建lua线程
lua_State * newLuaThread()
{
lua_State * sL = lua_newthread(L);
lua_pushvalue(L, -1);
int nRef = luaL_ref(L, LUA_REGISTRYINDEX);
lua_newtable(nLuaState);
lua_pushvalue(nLuaState, -1);
lua_setmetatable(nLuaState, -2);
lua_getglobal(nLuaState, "_G");
lua_setfield(nLuaState, -2, "__index");
lua_setupvalue(nLuaState, 1, 1);
lua_pop(L, 1);
return sL;
}
答案 0 :(得分:1)
luaL_loadbuffer(nLuaState, nBuffer, strlen(nBuffer), nullptr);
lua_newtable(nLuaState);
lua_pushvalue(nLuaState, -1);
lua_setmetatable(nLuaState, -2);
lua_getglobal(nLuaState, "_G");
lua_setfield(nLuaState, -2, "__index");
lua_pushvalue(nLuaState, -1);
lua_setglobal(nLuaState, nChunk);
lua_setupvalue(nLuaState, -2, 1);
lua_getglobal(nLuaState, nChunk);
lua_getfield(nLuaState, -1, nFun);
lua_pcall(nLuaState, 0, 0, 0);