package key calculation for require
Posted: Mon Oct 06, 2025 5:18 am
Both standard lua and the Factorio lua use the package.loaded table to manage files that have already been loaded. However, in Factorio, the standard implementation has been replaced by a custom implementation (it says so at https://lua-api.factorio.com/latest/aux ... -functions).
To allow circular references between packages, standard Lua allows one to do
to "predefine" the contents of the package.loaded table and resolve circular references.
This works in factorio as well, however, the key is way more complicated, for mod "X", the key is __X__/a/b/c.lua, totally independent if the package was loaded with require('a/b/c.lua') or require('a.b.c').
I ended up using this as the computation for the key: package.loaded['__' .. script.mod_name .. '__/' .. (...):gsub('%.', '/') .. '.lua'] = my_stuff
There has to be a piece of code somewhere in the C++ code base that does that computation. Would it be possible to expose it in the package table? e.g. if that would be exposed as a function called key (which should be able to take the ... varargs passed in when a package gets required, similar to regular lua, then it would be possible to simply write package.loaded[package.key(...)] = my_stuff which would be as close to "regular" lua as it gets.
To allow circular references between packages, standard Lua allows one to do
Code: Select all
local my_stuff = {}
package.loaded[...] = my_stuff
... more code here ...
return my_stuff
This works in factorio as well, however, the key is way more complicated, for mod "X", the key is __X__/a/b/c.lua, totally independent if the package was loaded with require('a/b/c.lua') or require('a.b.c').
I ended up using this as the computation for the key: package.loaded['__' .. script.mod_name .. '__/' .. (...):gsub('%.', '/') .. '.lua'] = my_stuff
There has to be a piece of code somewhere in the C++ code base that does that computation. Would it be possible to expose it in the package table? e.g. if that would be exposed as a function called key (which should be able to take the ... varargs passed in when a package gets required, similar to regular lua, then it would be possible to simply write package.loaded[package.key(...)] = my_stuff which would be as close to "regular" lua as it gets.