如何在Lua中包含配置文件以用于变量

在我的 Lua 脚本中,有些变量我想要放在一个 'settings.conf' 文件中,这样我就可以很容易地更改变量,而不需要深入代码。

在其他编程语言中,它们使用 'include',但在 Lua 中似乎不同,因为它会加载一个模块。我只需要加载一个配置文件来获取一些参数。

我应该使用哪个命令来实现这个功能?

点赞
用户1823636
用户1823636

你可以像这样做:

config.lua:

myconf = {
    param1 = "qwe";
    param2 = 7;
}

主程序:

package.path = '*.lua;' .. package.path
require "config"
print("config param1 = " .. myconf.param1 .. "\n")

在大多数情况下,这能够很好地工作。

2015-09-21 11:49:45
用户107090
用户107090

从另一个脚本执行Lua脚本的最简单方法是使用 dofile,它需要一个文件路径:

dofile"myconfig.lua"

dofile "/usr/share/myapp/config.lua"

使用dofile的问题是它可能会引发错误并中止调用脚本。如果您想处理错误,例如文件不存在、语法或执行错误,则使用pcall

local ok,e = pcall(dofile,"myconfig.lua")
if not ok then
  -- handle error; e has the error message
end

如果您想要更精细的控制,则使用loadfile,然后是一个函数调用:

local f,e = loadfile("myconfig.lua")
if f==nil then
  -- handle error; e has the error message
end
local ok,e = pcall(f)
if not ok then
  -- handle error; e has the error message
end
2015-09-21 11:50:29