【问题标题】:How to include config file for variables in Lua如何在 Lua 中包含变量的配置文件
【发布时间】:2015-09-21 19:59:15
【问题描述】:

在我的 lua 脚本中,我想将一些变量放入“settings.conf”文件中,这样我就可以轻松更改变量而无需深入研究代码。
在其他语言中,他们使用“包含”,但在 Lua 中似乎有所不同,因为它加载了 module。我只需要为一些参数加载配置文件。
我应该使用哪个命令?

【问题讨论】:

    标签: lua


    【解决方案1】:

    从另一个脚本执行 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
    

    【讨论】:

    • 最后你的解决方案更好。我在使用其他解决方案时遇到了一些奇怪的问题。
    【解决方案2】:

    你可以这样做:

    config.lua:

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

    主程序:

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

    这在大多数情况下都很有效。

    【讨论】:

    • 除非您想将新配置写入文件。
    • @hjpotter92,你的意思是如果我覆盖这个文件配置不会更新?对于我的困惑,我深表歉意,但我不完全理解你的说法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 2021-08-15
    • 1970-01-01
    • 2014-02-20
    • 2011-07-09
    • 2020-05-05
    • 2013-01-20
    相关资源
    最近更新 更多