Search code examples
luamodularitylove2d

Modular code structure in Lua


I've been working with Love2d recently to build a Conway's Game of Life implementation.

I really like the framework, but I haven't been able to figure out how to modularize my code, which I feel is crucial to solid code structure.

What I'm wanting to do is be able to import a file that has different functions in it and be able to access that through my main lua file. I have been able to write scripts and run entire files, but not specific functions.

Is there a way to do this in Lua? If so, how?

Thanks!


Solution

  • You can use the require function in LÖVE. It works similarly to how it works in Lua.

    -- lib.lua
    
    local lib = {} -- table to store the functions
    
    function lib.inc(x)
      return x + 1
    end
    
    return lib
    

    And here is how you require it in another file (for example, main.lua) and use it:

    local lib = require('lib')
    
    function love.load()
      print(lib.inc(1)) -- prints '2' in the terminal
    end