我需要将文件加载到Lua的变量中。
假设我有一个
name address email
每行之间有空格。我需要将包含x行此类文本的文本文件加载到某种对象中,或者至少将一行切割为由空格分隔的字符串数组。
在Lua中是否可能完成这种工作,应该如何实现?我对Lua还很陌生,但我在互联网上找不到相关信息。
您想了解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
) 组成的三个子字符串。一个真正的函数应该进行一些错误检查,以确保模式实际匹配。
如上所述:
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
然而,这并不涵盖您的名称中包含空格的情况。