Lua:如何避免循环要求 [英] Lua: How to avoid Circular Requires
本文介绍了Lua:如何避免循环要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在尝试执行循环要求时,如何避免Lua 5.1出现以下错误?
How can I avoid the following error from Lua 5.1 when attempting to do a circular require?
$ lua main.lua
lua: ./bar.lua:1: loop or previous error loading module 'foo'
stack traceback:
[C]: in function 'require'
./bar.lua:1: in main chunk
[C]: in function 'require'
./foo.lua:1: in main chunk
[C]: in function 'require'
main.lua:1: in main chunk
[C]: ?
文件结构
main.lua
require "foo"
require "bar"
print (Foo.getName())
print (Bar.getName())
foo.lua
require 'bar'
Foo = {}
Foo.name = 'foo'
function Foo:getName()
return Foo.name .. Bar.name
end
bar.lua
require 'foo'
Bar = {}
Bar.name = 'bar'
function Bar:getName()
return Bar.name .. Foo.name
end
预期产量
$ lua main.lua
foobar
barfoo
推荐答案
解决此问题的另一种方法是更改代码的结构,并将相互"功能提取到第三个模块中,这两个模块均Foo
和Bar
会要求.
Another way would to solve this issue would be to change the structure of the code and extract the "mutual" functionality into a third module, which both Foo
and Bar
would require.
这篇关于Lua:如何避免循环要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文