How do I set, via the lua C API, the environment table for a chunk of lua code prior to running it?

混江龙づ霸主 提交于 2019-12-04 16:17:48

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

Setting upvalues is done with lua_setupvalue. So, load your code first, then push the new environment and call lua_setupvalue the same way you would have called lua_setfenv before:

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 */

Also, from the end of your question:

The function lua_load allows specifying an environment, but seems to only be used for loading code and not running it.

This is not actually the case; load (the Lua function) lets you specify an environment, but lua_load (the C function) does not.

Also, while it is "only used for loading code, and not running it", this is the same as luaL_loadstring - indeed, luaL_loadstring is just a wrapper around it. lua_load is a lower-level API function that can be used to implement custom loaders (for example, loading code over the network, or from a compressed file). So if you're already comfortable loading code with luaL_loadstring before running it with lua_pcall, lua_load should look familiar.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!