包括文件、覆盖变量
我试图通过在代码末尾要求第二个来覆盖第一个 .lua 文件中的变量。
file1.lua
val = 1
require "file2"
file2.lua
val = 2
不幸的是,这似乎不起作用,因为在此之后 val 仍然是 1。我想出的解决方案是允许这些文件的潜在未来用户包含文件,这是一个新函数,我现在在初始化 Lua 时插入它:
function include(file)
dofile("path/since_dofile_doesnt_seem_to_use/package/path" .. file .. ".lua")
end
这与预期完全一样,但因为我还是新手Lua,我想知道是否有更好的解决方案。也许已经内置了一些东西?
更新:
我的问题是,我不小心在多个文件上多次需要 file2,并且 Lua 不会再次加载它来更改值。解决了。
I'm trying to overwrite the variables in my first .lua file, by requiring a second on, at the end of my code.
file1.lua
val = 1
require "file2"
file2.lua
val = 2
Unfortunately this doesn't seem to work, as val is still 1 after this. The solution I came up with, to allow the potential future users of those files to include files, is a new function, which I'm for now inserting when initializing Lua:
function include(file)
dofile("path/since_dofile_doesnt_seem_to_use/package/path" .. file .. ".lua")
end
This works exactly as expected, but since I'm still new to Lua, I'd like to know, if there might be a better solution. Maybe there's something already build in?
Update:
My problem was that I've accidentally required file2 multiple times, over multiple files, and Lua wouldn't load it again, to change the value. Solved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Lua 在名为
package.loaded
的表中跟踪代码中require
的所有文件。每次require
一个文件时,都会检查该表,如果表中已存在该模块名称,则不会加载该文件。如果表中不存在,则加载模块并将名称添加到表中。这样您就可以多次require
一个模块,但它只会在第一次运行。您可以通过在
require
包之后设置package.loaded[packagename] = nil
来解决这个问题。这样,当lua检查表中是否存在包名时,它就不会找到它,所以你可以根据需要多次require它。Lua keeps track of all the files you have
require
d in your code in a table calledpackage.loaded
. Every time a file isrequire
d, that table is checked, and if the module name exists in the table already, it is not loaded. If it does not exist in the table, the module is loaded and the name is added to the table. This way you canrequire
a module many times but it will only be run the first time.You can get around this by setting
package.loaded[packagename] = nil
afterrequire
ing the package. That way, when lua checks if the package name exists in the table, it will not find it, so you can require it as many times as you want.在 file2.lua 中
输出应该是
1
2
in file2.lua
output should be
1
2