Lua: Avoiding Circular Requirements

Problem

How can I avoid the following Lua 5.1 error when trying to make a circular request?

$ 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]: ? 

File structure

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 

Expected Result

 $ lua main.lua foobar barfoo 
+8
lua circular-dependency
source share
2 answers

Another way to solve this problem would be to change the structure of the code and extract the β€œmutual” functionality into the third module, which will require both Foo and Bar .

+10
source share

Decision

main.lua

 Foo = Foo or require "foo" Bar = Bar or require "bar" print (Foo.getName()) print (Bar.getName()) 

foo.lua

 Foo = {} Bar = Bar or require "bar" Foo.name = 'foo' function Foo:getName() return Foo.name .. Bar.name end return Foo 

bar.lua

 Bar = {} Foo = Foo or require "foo" Bar.name = 'bar' function Bar:getName() return Bar.name .. Foo.name end return Bar 

Explanation

Since you are setting global variables, you can check if a file (aka; global already defined) is required before trying another:

 Bar = Bar or require "bar" 

Then your bar.lua will have to return the definition of Bar;

 Bar = {} -- ... return Bar 

This will not completely solve the problem, since bar.lua expects Foo to determine. To solve this problem, you can define a dummy variable with the same name:

 Foo = {} Bar = Bar or require "bar" 

This is only possible because you delay the use of Foo until the function is called. If you want to call Foo.name from the bar.lua , you will have the same circular dependency problem.

+8
source share

All Articles