Use of pushglobaltable and setfenv in Lua5.3

来源:互联网 发布:java毕业论文任务书 编辑:程序博客网 时间:2024/06/01 08:46

Use of pushglobaltable and setfenv in Lua5.3

up vote1down votefavorite

how to get luathread function with same function name in diffent luathreads in Lua 5.3? use getglobal in 5.1 work sucess, but under 5.3 work error,

this code is main run call luathread functions

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);

//---- result of lua 5.1

12
23

//----- result of lua 5.3

23
23

why result 5.3 is diffent from 5.1?

this code is create lua thread in lua 5.1

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;}

this code is create lua thread in lua 5.3

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;}
shareimprove this question
 
1 
setuservalue doesn't replace the use of function environments it replaces the user of userdata environments. The replacement for function environments in lua 5.2+ is _ENV. – Etan Reisner May 4 '15 at 11:22 
 
thank you! i spend more time on setupvalue, but also not work – 冷冷爱 May 5 '15 at 2:51 

1 Answer

activeoldestvotes
up vote1down vote

spend 5 days find the correct answer is:

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);
0 0