Use of pushglobaltable and setfenv in Lua5.3

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

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值