我正在使用lua(love2d引擎)开发游戏,现在我想将代码分离到多个文件中。问题是:我不知道该怎么做,因为我正在通过游戏开发来学习lua。我知道有可能,但是我发现的答案没有用。如果有人可以用“人类语言”告诉我如何做到这一点,并给我一个示例(以代码形式),我将非常感谢。
亲切的问候,汤姆
您正在寻找的是所谓的模块。模块或多或少是一个单独的文件,其中包含一些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
Run Code Online (Sandbox Code Playgroud)
可以在这里找到有关Lua模块的出色教程:http : //lua-users.org/wiki/ModulesTutorial