我的游戏引擎界面是使用标记语言和 Lua 构建的,类似于 HTML 和 javascript。因此,视觉元素将具有 UI 事件的处理程序,例如鼠标移动或单击,并且每次运行处理程序时,引擎将检查它是否已编译,如果未编译,将通过 luaL_loadstring< 进行编译。/
。处理程序可以通过元素复制或分配来共享 (this.onclick = that.onclick
)。
如何在运行前设置一段lua代码的环境?这个想法是使元素和事件特定的数据可用于 block ,并链接到父 UI 元素的环境。 Lua 5.2 changes删除了 lua_setfenv
,所以我不确定如何完成此操作。函数lua_load
允许指定一个环境,但似乎只用于加载代码而不是运行它。
最佳答案
来自reference manual :
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.)
设置upvalues是用lua_setupvalue
完成的.因此,首先加载您的代码,然后推送新环境并调用 lua_setupvalue
,就像您之前调用 lua_setfenv
一样:
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.
实际情况并非如此; load
(Lua 函数)允许您指定一个环境,但 lua_load
(C 函数)不能。
此外,虽然它“仅用于加载代码,而不是运行它”,但这与 luaL_loadstring
相同 - 实际上,luaL_loadstring
只是一个包装器它。 lua_load
是一个较低级别的 API 函数,可用于实现自定义加载器(例如,通过网络或从压缩文件加载代码)。因此,如果您在使用 lua_pcall
运行代码之前已经习惯使用 luaL_loadstring
加载代码,那么 lua_load
应该看起来很熟悉。
关于c++ - 在运行它之前,如何通过 lua C API 为一段 lua 代码设置环境表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19167986/