关于C#:在运行它之前,如何通过lua C API为一大堆lua代码设置环境表?

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事件的处理程序,例如鼠标移动或单击,并且每次运行处理程序时,引擎都会检查其是否已编译,如果不是,则将通过luaL_loadstring对其进行编译。可以通过元素复制或分配(this.onclick = that.onclick)共享处理程序。

在运行之前,如何设置大量lua代码的环境?这个想法是使特定于元素和事件的数据可用于块,并且还链接到父UI元素的环境。 Lua 5.2更改已删除lua_setfenv,因此我不确定如何完成此操作。函数lua_load允许指定环境,但似乎仅用于加载代码而不运行它。


摘自参考手册:

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

使用lua_setupvalue设置升值。因此,首先加载代码,然后推送新环境并以与以前调用lua_setfenv相同的方式调用lua_setupvalue

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.

实际上并非如此; load(Lua函数)使您可以指定环境,而lua_load(C函数)则不能。

此外,虽然它"仅用于加载代码,而不用于运行代码",但它与luaL_loadstring相同-实际上,luaL_loadstring只是它的包装。 lua_load是一个较低级的API函数,可用于实现自定义加载程序(例如,通过网络或从压缩文件加载代码)。因此,如果在使用lua_pcall运行代码之前已经习惯于使用luaL_loadstring加载代码,则lua_load应该看起来很熟悉。