Recommended way to have 2+ modules recursively refer to each other in Lua 5.2

旧时模样 提交于 2019-12-03 07:40:59

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.

Another method, suggested by Owen Shepherd on the lua-l mailing list:

If we set package.loaded[current-module-name] at the top of each module, then any other module required later can refer to the current (possibly incomplete) module.

A.lua:

local A = {}
package.loaded[...] = A

local B = require 'B'

function A.foo()
    return B.bar()
end

function A.baz()
    return 42
end

return A

B.lua:

local B = {}
package.loaded[...] = B

local A = require 'A'

function B.bar()
    return A.baz()
end

return B

This will not work everywhere. For example if B's initialization depends on A.baz then it will fail if A is loaded first, because B will see an incomplete version of A in which baz is not yet defined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!