关于C#:在Lua5.3中使用pushglobaltable和setfenv

Use of pushglobaltable and setfenv in Lua5.3

如何在Lua 5.3中的不同luathreads中获得具有相同函数名称的luathread函数?
在5.1工作成功中使用getglobal,但在5.3工作错误下,

此代码是luathread函数的主要运行调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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线程的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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线程的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
}


花费5天找到正确的答案是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);