我正在开发lua(love2d引擎)中的游戏,现在我想将我的代码分离为多个文件。问题是:我不知道该怎么做,因为我通过游戏开发来学习lua。我知道这是可能的,但我发现的答案并非有用。如果有人能告诉我如何以“人类语言”来做到这一点,并给我一个例子(代码),我非常感谢。如何在lua中使用多个文件
亲切的问候, 汤姆
我正在开发lua(love2d引擎)中的游戏,现在我想将我的代码分离为多个文件。问题是:我不知道该怎么做,因为我通过游戏开发来学习lua。我知道这是可能的,但我发现的答案并非有用。如果有人能告诉我如何以“人类语言”来做到这一点,并给我一个例子(代码),我非常感谢。如何在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
上Lua模块的优良的教程可以在这里找到:http://lua-users.org/wiki/ModulesTutorial
[文档上SO](http://stackoverflow.com/documentation/lua/1148/writing-和使用模块#t = 201612021029042253729) –