如何在lua中使用多个文件
我正在用lua(love2d引擎)开发一个游戏,现在我想把我的代码分割成多个文件。问题是:我不知道怎么做,因为我正在通过游戏开发学习lua。我知道这是可能的,但我找到的答案没有用。如果有人能用“人类语言”告诉我如何做到这一点,并给我一个例子(用代码),我非常感谢 亲切问候,,如何在lua中使用多个文件,lua,Lua,我正在用lua(love2d引擎)开发一个游戏,现在我想把我的代码分割成多个文件。问题是:我不知道怎么做,因为我正在通过游戏开发学习lua。我知道这是可能的,但我找到的答案没有用。如果有人能用“人类语言”告诉我如何做到这一点,并给我一个例子(用代码),我非常感谢 亲切问候,, Tom你要找的是一种叫做模块的东西。模块或多或少是一个单独的文件,其中包含一些Lua代码,您可以从代码中的多个位置加载和使用这些代码。您可以使用require()关键字加载模块 例如: -- pathfinder.lua
Tom你要找的是一种叫做模块的东西。模块或多或少是一个单独的文件,其中包含一些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模块的优秀教程可以在这里找到:您正在寻找的是一种叫做模块的东西。模块或多或少是一个单独的文件,其中包含一些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模块的优秀教程:我想我明白了,但我仍然有一个问题:如何将变量从一个文件传递到另一个文件?不管怎样,已经解决了:p对于那些想知道的人:只需将变量添加到表中!我想我明白了,但我仍然有一个问题:如何将变量从一个文件传递到另一个文件?没关系,已经解决了:P对于那些想知道的人:只需将变量添加到表中!