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

Sku*_*uta 6 lua load file lua-table

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

比方说我得到了

name address email
Run Code Online (Sandbox Code Playgroud)

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

在Lua这种工作是否可行,我应该怎么做?我对Lua很新,但我在互联网上找不到任何相关内容.

Nor*_*sey 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
Run Code Online (Sandbox Code Playgroud)

此函数只捕获由非空格(%S)字符组成的三个子字符串.一个真正的函数会有一些错误检查,以确保模式实际匹配.


RCI*_*CIX 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
Run Code Online (Sandbox Code Playgroud)

但是,这并不包括您的名字中包含空格的情况.