lua

How to use multiple files in lua


I'm working on a game in lua(love2d engine), and now I want to separate my code to multiple files. The problem is: I don't know how to do this, because I'm learning lua via game development. I know it's possible, but the answers I found were not usefull. If anyone can tell me how to do this in "human language", and give me an example(in code), I'm very thankful.

Kind regards, Tom


Solution

  • What you are looking for is something called modules. A module is more or less an individual file containing some Lua code that you can load and use from multiple places in your code. You load the module using the require() keyword.

    Example:

    pathfinder.lua

    -- Lets create a Lua module to do pathfinding
    -- We can reuse this module wherever we need to get a path from A to B
    
    -- this is our module table
    -- we will add functionality to this table
    local M = {}
    
    -- Here we declare a "private" function available only to the code in the
    -- module
    local function get_cost(map, position)
    end
    
    --- Here we declare a "public" function available for users of our module
    function M.find_path(map, from, to)
        local path
        -- do path finding stuff here
        return path
    end
    
    -- Return the module
    return M
    

    player.lua

    -- Load the pathfinder module we created above
    local pathfinder = require("path.to.pathfinder")    -- path separator is ".", note no .lua extension!
    
    local function move(map, to)
        local path = pathfinder.find_path(map, get_my_position(), to)
        -- do stuff with path
    end
    

    An excellent tutorial on Lua modules can be found here: http://lua-users.org/wiki/ModulesTutorial