Lua: How to avoid Circular Requires

后端 未结 2 1250
萌比男神i
萌比男神i 2020-12-17 20:13

Problem

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 previo         


        
相关标签:
2条回答
  • 2020-12-17 20:52

    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.

    0 讨论(0)
  • 2020-12-17 20:59

    Solution

    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 to see if the file has already been required (aka; the global already defined) before attempting another require:

    Bar = Bar or require "bar"
    

    Your bar.lua would then have to return the definition of Bar;

    Bar = {}
    -- ...
    return Bar
    

    This wont entirely resolve the issue as bar.lua is expecting Foo to be defined. To resolve this, you can define a dummy variable with the same name:

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

    This is only possible because you are deferring the usage of Foo to when the function is called. If you wanted to call Foo.name from within the scope of bar.lua, you would end up with the same circular dependency issue.

    0 讨论(0)
提交回复
热议问题