在Lua 5.2中使2个以上模块递归引用的推荐方式 [英] Recommended way to have 2+ modules recursively refer to each other in Lua 5.2
本文介绍了在Lua 5.2中使2个以上模块递归引用的推荐方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法
- 两个Lua模块(我们叫它们
A
和B
) - 每个模块都使用彼此的功能,因此它们必须彼此
require
- 第三个模块(我们称其为
C
)可以使用A
,但不能使用B
,例如
- Two Lua modules (let's call them
A
andB
) - Each module uses functions from the other, so they must
require
each other - A third module (let's call it
C
) can useA
but notB
e.g.
C.lua
:
local A = require 'A'
-- ...
A.foo()
- 可能还有另一个模块
D
需要B
,但不需要A
和/或E
同时需要A
和B
-
A
或B
或它们的成员都不应添加到全局名称空间. - 避免使用
module
和setfenv
函数(在Lua 5.2中已弃用) - There may be another module
D
that requiresB
but notA
and/orE
requiring bothA
andB
- Neither
A
norB
nor their members should be added to the global namespace. - Avoid using the
module
andsetfenv
functions (deprecated in Lua 5.2)
相关: Lua-我该如何使用另一个库?(请注意:此解决方案无法处理循环依赖项.)
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
这篇关于在Lua 5.2中使2个以上模块递归引用的推荐方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文