How do I set, via the lua C API, the environment table for a chunk of lua code prior to running it?
我的游戏引擎界面使用类似于HTML和javascript的标记语言和Lua构建。这样,可视元素将具有UI事件的处理程序,例如鼠标移动或单击,并且每次运行处理程序时,引擎都会检查其是否已编译,如果不是,则将通过
在运行之前,如何设置大量lua代码的环境?这个想法是使特定于元素和事件的数据可用于块,并且还链接到父UI元素的环境。 Lua 5.2更改已删除
摘自参考手册:
You can use load (or loadfile) to load a chunk with a different environment. (In C, you have to load the chunk and then change the value of its first upvalue.)
使用
1 2 3 4 5 | luaL_loadfile(L,"file.lua"); /* load and compile handler */ lua_getglobal(L,"my_environment"); /* push environment onto stack */ lua_setupvalue(L, -2, 1); /* pop environment and assign to upvalue#1 */ /* any other setup needed */ lua_pcall(L, ...); /* call handler */ |
另外,从您的问题结尾处开始:
The function
lua_load allows specifying an environment, but seems to only be used for loading code and not running it.
实际上并非如此;
此外,虽然它"仅用于加载代码,而不用于运行代码",但它与