unofficial Lua FAQ在Lua有一个关于沙箱的条目。 我的猜测是,您可以轻松地将该逻辑转置为您的C/C++代码。请参阅LuaFiveTo on the lua-users wiki。
修正
这的确不是因为它似乎微不足道。但最终的观点很简单:加载你的块,按下_ENV表,使用lua_setupvalue(L,-2,1)
。重要的是表格应该位于堆栈的顶部。
作为一个小例子,使用2-环境经由元表默认为_G用于读取的东西:
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
int main(void){
lua_State *L = luaL_newstate();
char *file1 = "file1.lua";
char *file2 = "file2.lua";
luaL_openlibs(L);
luaL_loadfile(L,file2); // S: 1
luaL_loadfile(L,file1); // S: 2
lua_newtable(L); // ENV for file 1: S: 321
lua_newtable(L); // ENV for file 2: S: 4321
//lets have each function have its metatable, where missed lookups are
//instead looked up in the global table _G
lua_newtable(L); // metatable S: 54321
lua_getglobal(L,"_G"); // pushes _G, which will be the __index metatable entry S: 654321
lua_setfield(L,-2,"__index"); // metatable on top S: 54321
lua_pushvalue(L,-1); // copy the metatable S: 554321
lua_setmetatable(L,-3); // set the last copy for env2 S: 54321
lua_setmetatable(L,-3); // set the original for env1 S: 4321
// here we end up having 2 tables on the stack for 2 environments
lua_setupvalue(L,1,1); // first upvalue == _ENV so set it. S: 321
lua_setupvalue(L,2,1); // set _ENV for file S: 21
// Remaining on the stack: 2 chunks with env set.
lua_pcall(L,0,LUA_MULTRET,0);
lua_pcall(L,0,LUA_MULTRET,0);
lua_close(L);
return 0;
}
而对于2的Lua文件:
-- file1.lua
function init()
A="foo"
print("Hello from file1")
print(A)
end
init()
-- file2.lua
-- this shows that stuff defined in file1 will not polute the environment for file2
print("init function is",tostring(init))
function init()
A="bar"
print("Hello from file2")
print(A)
end
init()
这就是为什么我一直坚持用LUA 5.1在我自己的项目,现在的原因之一。我相信v5.2'load'和'loadfile'函数可以让你指定一个环境;他们可能是开始寻找解决方案的最佳场所。 – Rook
谢谢,但我读了关于加载和加载文件,但我找不到解决方案 – Steve
'setuservalue'绝对不是尝试操作环境时使用的正确函数。但是,lua文档似乎对你应该做的事情不太清楚。 'lua_load'表示一个与被加载的块相关联的单值被设置为它的环境,但没有提到你如何去关联一个upvalue和来自C的块。如果你是从lua加载块,那么lua版本的'load'函数看起来应该正确设置环境。 – Rook