包括文件,覆盖变量 [英] Including files, overwriting variables
问题描述
我正在尝试通过在代码末尾再打开第二个.lua文件来覆盖我的第一个.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
file1.lua
val = 1
require "file2"
file2.lua
file2.lua
val = 2
不幸的是,这似乎不起作用,因为在此之后val仍然为1.我想出的解决方案是一项新功能,允许这些文件的潜在未来用户包括文件,这是我现在要在初始化Lua时插入的一个新功能:
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
这完全符合预期,但是由于我还是Lua的新手,所以我想知道是否有更好的解决方案.也许已经内置了某些东西?
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?
更新:
我的问题是我不小心多次需要file2,超过了多个文件,而Lua不会再次加载它来更改值.解决了.
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.
推荐答案
Lua在名为package.loaded
的表中跟踪代码中所有具有require
d的文件.每次require
d文件时,都会检查该表,并且如果该表中已经存在模块名称,则不会加载该文件名.如果表中不存在该模块,则将加载模块,并将名称添加到表中.这样,您可以多次require
一个模块,但只能在第一次运行.
Lua keeps track of all the files you have require
d in your code in a table called package.loaded
. Every time a file is require
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 can require
a module many times but it will only be run the first time.
您可以通过在打包require
之后设置package.loaded[packagename] = nil
来解决此问题.这样,当lua检查表中是否存在包名称时,它将找不到它,因此您可以根据需要多次.
You can get around this by setting package.loaded[packagename] = nil
after require
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.
这篇关于包括文件,覆盖变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!