gpt4 book ai didi

lua - 5.2 中的沙盒嵌入式 Lua/为 lua.file 中的函数设置环境

转载 作者:行者123 更新时间:2023-12-04 11:41:52 33 4
gpt4 key购买 nike

假设我至少有两个 lua 脚本文件。

测试1.lua
测试2.lua

两者都定义了一个 init 函数和其他具有相似名称的函数。

我如何使用 Lua 5.2 将使用 c++/c 的每个脚本文件加载到一个单独的环境中,以便相同的函数名称不会发生冲突 - 我发现了一个 5.1 的示例代码,它对我不起作用(因为 setenv 消失了,而 lua_setuservalue 没有似乎工作)

sample 在这里Calling lua functions from .lua's using handles?

基本上,如果我用 setuservalue 替换 setenv - 我会遇到访问冲突。

最佳答案

unofficial Lua FAQ有一个关于 Lua 沙箱的条目。
我的猜测是,您可以轻松地将该逻辑转换为您的 C/C++ 代码。

另见 LuaFiveTo on the lua-users wiki .

更正

它确实没有看起来那么琐碎。但最后重点很简单:加载块,推送 _ENV 表,使用 lua_setupvalue(L,-2,1) .重要的是该表应该在堆栈的顶部。

作为一个小例子,使用默认为 _G 的 2 个环境通过元表读取内容:

#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.2 中的沙盒嵌入式 Lua/为 lua.file 中的函数设置环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11013727/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com