【问题标题】:How to load text file into sort of table-like variable in Lua?如何将文本文件加载到 Lua 中的类似表的变量中?
【发布时间】:2010-12-25 21:02:00
【问题描述】:

我需要将文件加载到 Lua 的变量中。

假设我得到了

name address email

每个之间都有空格。我需要将包含 x 多行这样的行的文本文件加载到某种对象中 - 或者至少将一行剪切为由空格分隔的字符串数组。

这种工作在 Lua 中可行吗?我应该怎么做?我对 Lua 很陌生,但在 Internet 上找不到任何相关内容。

【问题讨论】:

  • 注意:语言的名称不是首字母缩写词,它是一个专有名称(葡萄牙语中的月亮),所以 Lua 不是 LUA。

标签: file lua load lua-table


【解决方案1】:

如果您可以控制输入文件的格式,您最好按照here 所述以 Lua 格式存储数据。

如果没有,请使用io library 打开文件,然后使用string library 喜欢:

local f = io.open("foo.txt")
while 1 do
    local l = f:read()
    if not l then break end
    print(l) -- use the string library to split the string
end

【讨论】:

    【解决方案2】:

    扩展 uroc 的答案:

    local file = io.open("filename.txt")
    if file then
        for line in file:lines() do
            local name, address, email = unpack(line:split(" ")) --unpack turns a table like the one given (if you use the recommended version) into a bunch of separate variables
            --do something with that data
        end
    else
    end
    --you'll need a split method, i recommend the python-like version at http://lua-users.org/wiki/SplitJoin
    --not providing here because of possible license issues
    

    但是,这不会涵盖您的姓名中包含空格的情况。

    【讨论】:

      【解决方案3】:

      您想了解Lua patterns,它们是string library 的一部分。这是一个示例函数(未测试):

      function read_addresses(filename)
        local database = { }
        for l in io.lines(filename) do
          local n, a, e = l:match '(%S+)%s+(%S+)%s+(%S+)'
          table.insert(database, { name = n, address = a, email = e })
        end
        return database
      end
      

      这个函数只抓取三个由非空格 (%S) 字符组成的子字符串。真正的函数会进行一些错误检查以确保模式确实匹配。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-13
        • 1970-01-01
        • 2023-03-14
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多