Is there a way to have
A
and B
)require
each otherC
) can use A
but not B
e.g.C.lua
:
local A = require 'A'
-- ...
A.foo()
D
that requires B
but not A
and/or E
requiring both A
and B
A
nor B
nor their members should be added to the global namespace.module
and setfenv
functions (deprecated in Lua 5.2)Related: Lua - how do I use one lib from another? (note: this solution does not handle circular dependencies.)
I found quite a simple way to do it:
A.lua
:
local A = {}
local B
function A.foo()
B = B or require 'B'
return B.bar()
end
function A.baz()
return 42
end
return A
B.lua
:
local B = {}
local A
function B.bar()
A = A or require 'A'
return A.baz()
end
return B