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.
Lua keeps track of all the files you have
required in your code in a table calledpackage.loaded. Every time a file isrequired, 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 canrequirea module many times but it will only be run the first time.You can get around this by setting
package.loaded[packagename] = nilafterrequireing 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.