我正在開發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) –