如何在lua中使用多个文件

时间:2016-12-02 09:35:28

标签: lua multiple-files

我正在使用lua(love2d引擎)开发游戏,现在我想将我的代码分成多个文件。问题是:我不知道该怎么做,因为我正在通过游戏开发学习lua。我知道这是可能的,但我找到的答案并没有用。如果有人能用“人类语言”告诉我如何做到这一点,并给我一个例子(代码中),我非常感谢。

亲切的问候, 汤姆

1 个答案:

答案 0 :(得分:4)

您正在寻找的是模块。模块或多或少是包含一些Lua代码的单个文件,您可以从代码中的多个位置加载和使用这些代码。您使用require()关键字加载模块。

示例:

-- 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

可以在此处找到有关Lua模块的优秀教程:http://lua-users.org/wiki/ModulesTutorial