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

File 如何将文本文件加载到Lua中类似于表的变量中?,file,lua,load,lua-table,File,Lua,Load,Lua Table,我需要将文件加载到Lua的变量中 假设我有 name address email 每一个之间都有空间。我需要将包含x多行的文本文件加载到某种对象中,或者至少将其中一行剪切为字符串数组除以空格 这种工作在Lua可能吗?我应该怎么做?我对Lua很陌生,但我在Internet上找不到任何相关信息。如果您可以控制输入文件的格式,最好按照所述的Lua格式存储数据 如果没有,请使用打开文件,然后使用类似的方法: 要详细介绍uroc的答案: local file = io.open("filename.tx

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

假设我有

name address email
每一个之间都有空间。我需要将包含x多行的文本文件加载到某种对象中,或者至少将其中一行剪切为字符串数组除以空格


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

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

如果没有,请使用打开文件,然后使用类似的方法:


要详细介绍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
但是,这不包括您的姓名中有空格的情况。

您想了解的内容,这些内容是本手册的一部分。下面是一个示例函数(未测试):


此函数仅获取由非空格(
%S
)字符组成的三个子字符串。真正的函数将进行一些错误检查,以确保模式实际匹配。

注意:该语言的名称不是首字母缩略词,而是一个专有名称(葡萄牙语表示moon),因此Lua不是Lua。
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
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