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

假设我有

name address email

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

这种工作在 Lua 中可行吗?我应该怎么做?我对 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

不过,这将不包括你的名字有空格他们的情况。

其他提示

您想了解 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)字符3名的子串。一个真正的功能会有些错误检查,以确保该模式实际上相匹配。

如果您可以控制输入文件的格式,那么最好将数据存储为 Lua 格式,如下所述 这里.

如果没有,请使用 io库 打开文件,然后使用 字符串库 喜欢:

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top