如何在Lua中将文本文件加载到类似表格的变量中?

6

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

假设我有一个

name address email

每行之间有空格。我需要将包含x行此类文本的文本文件加载到某种对象中,或者至少将一行切割为由空格分隔的字符串数组。

在Lua中是否可能完成这种工作,应该如何实现?我对Lua还很陌生,但我在互联网上找不到相关信息。


3
请注意:这种语言的名称不是缩写,而是一个适当的名称(葡萄牙语中的“月亮”),因此应该写成Lua而不是LUA。 - RCIX
3个回答

11

您想了解Lua 模式,它们是字符串库的一部分。以下是一个示例函数(未经测试):

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) 组成的三个子字符串。一个真正的函数应该进行一些错误检查,以确保模式实际匹配。


9
为了补充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格式存储,如此处所述here
如果不能控制,则使用io库打开文件,然后使用string库,例如:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接