【问题标题】:How to load host.conf file variables in lua script如何在 lua 脚本中加载 host.conf 文件变量
【发布时间】:2021-01-12 19:33:21
【问题描述】:

我需要在 lua 脚本中从 .conf 文件加载配置变量,并使用这些变量连接到数据库。我试过使用:

require "host.conf"
loadfile("host.conf") - error with unexpected token '#' 
os.execute("pathToConfFile/host.lua") - and I have created a lua host file with variables in bash shell
io.popen("host.conf") etc..

这些解决方案均无效。 有没有办法在 lua 中使用现有的 host.conf 文件,并避免意外的令牌错误? 谢谢你的建议。

【问题讨论】:

  • 首先,您是否研究过这些功能以及它们的实际作用?每个都有自己的目的,这意味着它们不可互换。其次,您打算如何连接到您提到的数据库?您是否使用具有 Lua API 的库?最后,您使用的是什么系统和版本的 Lua?
  • Anw host.conf 的内容是什么(审查敏感数据或课程)。
  • 意外标记 '#' 指向 host.conf 中的 cmets,因此不是 Lua 脚本。
  • 你考虑过阅读 Lua 手册吗?我不确定您通过将文件名填充到一些随机函数中来达到什么目的。你怎么能指望这样做有什么有用的呢?

标签: lua


【解决方案1】:
local original = io .open('host.conf')
local hostconf = {}  --  copy contents into Lua table

for line in original :lines() do
    table .insert( hostconf, line )
end ; io .close( original )

print( hostconf[1] )  --  prints line 1

您尚未指定 host.conf 的格式,但您可能希望更好地解析它,而不是仅仅将内容放入列表中。也许根据分隔符(逗号,空格,变量和值之间的任何内容)将每一行分成头/尾

【讨论】:

    【解决方案2】:

    感谢所有提供帮助的人。我的问题并不准确,在我问及对此感到抱歉之前,我还有更多需要学习的东西。这是我用来解决问题的方法。

    local open = io.open
    
    local function read_file(path)
        local file = open(path, "r")
        if not file then return nil end
        local content = file:read "*a" -- *a or *all reads the whole file
    
        local lines = {}
    
        for line in io.lines(path) do
            --print(line);
            if(line:find(var)~=nil)then
               local varStart=string.len(var)+2
               local varEnd=string.len(line)
               var=string.sub(line,varStart,varEnd)
               print(var);
            end
    --repeat for every line
        
        end
        file:close()
        return lines;
    end
    
    local fileContent = read_file("path");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 2021-07-11
      • 2023-01-17
      相关资源
      最近更新 更多