circular dependency management
Posted: Mon Sep 29, 2025 5:07 am
Hi,
so I have two files, A.lua and B.lua:
A.lua:
B.lua:
This works fine. No matter which file is required first (A or B), it loads the other file and then continues without falling into a recursive loop.
But it is ugly. Is there really no better way to create the loaded key than doing this dance:
It would be nice if we can have some function to call from a file with the `...` as argument that returns the needed key for the package.loaded table. As the game itself does that, such a function must exist somewhere.
so I have two files, A.lua and B.lua:
A.lua:
Code: Select all
local A = {}
-- manage circular dependencies
local _pkgname = ...
package.loaded['__' .. script.mod_name .. '__/' .. _pkgname:gsub('%.', '/') .. '.lua'] = A
-- manage circular dependencies
local B = require('some.thing.B')
Code: Select all
local B = {}
-- manage circular dependencies
local _pkgname = ...
package.loaded['__' .. script.mod_name .. '__/' .. _pkgname:gsub('%.', '/') .. '.lua'] = B
-- manage circular dependencies
local A = require('some.thing.A')
But it is ugly. Is there really no better way to create the loaded key than doing this dance:
Code: Select all
local _pkgname = ...
package.loaded['__' .. script.mod_name .. '__/' .. _pkgname:gsub('%.', '/') .. '.lua'] = ... the main table of the file ...