您的位置:首页 > 编程语言 > Lua

Use of pushglobaltable and setfenv in Lua5.3

2016-11-17 18:04 459 查看


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


c++ lua
shareimprove
this question
edited May
5 '15 at 4:17

asked May 4 '15 at 10:13





冷冷爱
163

 
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 
add
a comment


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


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐