Search code examples
moduleluacircular-dependencylua-5.2

Recommended way to have 2+ modules recursively refer to each other in Lua 5.2


Is there a way to have

  • Two Lua modules (let's call them A and B)
  • Each module uses functions from the other, so they must require each other
  • A third module (let's call it C) can use A but not B e.g.

C.lua:

local A = require 'A'

-- ...

A.foo()
  • There may be another module D that requires B but not A and/or E requiring both A and B
  • Neither A nor B nor their members should be added to the global namespace.
  • Avoid using the module and setfenv functions (deprecated in Lua 5.2)

Related: Lua - how do I use one lib from another? (note: this solution does not handle circular dependencies.)


Solution

  • 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