5.1 setfenv,但5.3可以使用lua_getglobal(l1, "_G");


 5.1使用法
lua_State *L = luaL_newstate();
luaL_openlibs(L);

dostring(L, "function f1() my_var = 100 print('var set') end");/* create func on state */
/* ^-- a wrapper which does loadstring + pcall with error handling */

lua_State *l1 = lua_newthread(L);

lua_pushthread(l1);              /* l1: t                               */
lua_newtable(l1);                /* l1: t T1{}                          */
lua_newtable(l1);                /* l1: t T1{} T2{}                     */
lua_getglobal(l1, "_G");         /* l1: t T1{} T2{} _G                  */为了print函数能正常使用,全局表
lua_setfield(l1, -2, "__index"); /* l1: t T1{} T2{} ( T2.__index = _G)  */
lua_setmetatable(l1, -2);        /* l1: t T1 ( T1{}.mt = T2 )           */
if (!lua_setfenv(l1, -2))        /* l1: t (t.fenv = T1)                 */
   printf("setfenv fail!\n"); 
lua_pop(l1, 1);

dostring(l1, "print('l1: ', my_var)");       /* --> nil (expected) */
dostring(l1, "f1()  print('l1: ', my_var)"); /* --> l1: 100  (ok)  */
dostring(L, "print('L: ', my_var)");         /* --> L:  100  (No!) */

Am I doing anything wrong here ? (I don't want to load the function on the threads, because there can be a lot of them, and loading them once on the state seems to be the right approach)

--Edit--

The solution, seems to be:

  • create a new env table for each thread (with __index = _G)
  • for each function which runs within it, do setfenv(f1, getfenv(0))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值