我想知道如何在Lua脚本之间共享全局变量。
我试着用require自己做这件事,但它不像我预期的那样有效。
这是我的简单示例代码。
在test.lua中
num = 2在A.lua中
require(`test`);
num = 5在B.lua中
require(`test`);
print(num);如果首先运行A.lua,然后运行B.lua,则得到以下结果:
2但是我希望得到5,因为我在A.lua中将变量值修改为2。
有可能实现我想要的吗?(我想举个例子)
发布于 2018-07-13 13:44:11
您目前所做的工作如下:
lua A.lua
> lua process starts
> loading A.lua
> loading test.lua (because it is required by A.lua)
> set global "num" to value 2
> set global "num" to value 5
> lua process exits (A.lua finished)
lua B.lua
> lua process starts
> loading B.lua
> loading test.lua (because it is required by B.lua)
> set global "num" to value 2
> print global "num" (which was set to 2 by test.lua)
> lua process exits (B.lua finished)要打印值5,脚本应该如下所示:
-- test.lua
num = 2
-- A.lua
require("test")
num = 5
-- B.lua
require("test")
require("A")
print(num)这将导致:
lua B.lua
> lua process starts
> loading B.lua
> loading test.lua (because it is required by B.lua)
> set global "num" to value 2
> loading A.lua (because it is required by B.lua)
> skip loading test.lua (has already been loaded)
> set global "num" to value 5
> print global "num"
> lua process exits (B.lua finished)编辑:我看到您正在使用Lua的C,而不是Lua二进制文件来执行您的脚本。使用编程api,您应该能够通过使用相同的lua状态(通常存储在C变量“L”中)执行A.lua和B.lua来获得所需的结果。
发布于 2018-07-13 13:54:58
a.lua
a = 5b.lua
require('a')
a = 2test.lua
require('b')
print(a)您应该得到2,因为需求链是从上到下工作的,如果您只是运行每个文件-- lua只执行这个小的uniq执行时间,那么就不会有持久的this不同的执行,所以您需要根据需要执行。
https://stackoverflow.com/questions/51326066
复制相似问题