問題
如何避免以下錯誤從Lua 5.1試圖做循環需要?Lua:如何避免循環需要
$ 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
密切相關(但對於Lua5.2,並避免全局變量):http:// stackoverflow。com/questions/8248698/recommended-way-to-have-2-modules-recursively-refer-to-each-other-in-lua-5-2 – finnw