【发布时间】:2018-07-17 10:20:40
【问题描述】:
我的代码:
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
//Script A
luaL_dostring(L, "A = {} A.num = 3");
//Script B
luaL_dostring(L, "B = {} function B.update() return A.num * 2 end");
//Script C
luaL_dostring(L, "print(B.update())");
lua_close(L);
结果:6
但是,如果我将表 A 和 B 设为本地,如下所示:
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
//Script A
luaL_dostring(L, "local A = {} A.num = 3");
//Script B
luaL_dostring(L, "local B = {} function B.update() return A.num * 2 end");
//Script C
luaL_dostring(L, "print(B.update())");
lua_close(L);
它不输出任何东西。
如何使第二个代码工作,两者之间更推荐的设计是什么?
附加问题:将所有函数和变量放在每个 .lua 文件的唯一命名表中是 Lua 中避免每个文件之间名称冲突的常用技术吗?
【问题讨论】:
-
局部变量不能从其词法范围之外访问。它们的词法范围在定义它们的块内。每个
dostring引入单独的块。 -
始终检查错误!第二个示例中的
luaL_dostring(L, "print(B.update())");将失败,并显示类似failed to index nil global "B"
标签: lua