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
A standard way to do this in any language is to introduce a mediator. Modules can then publish and subscribe to the mediator. http://en.wikipedia.org/wiki/Mediator_pattern
An example of this in my languages is mvccontrib bus, IEventAggregator, and MVVM Lite Messenger class. They all do the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With