如何将文本文件加载到Lua中的类表变量中?
题
我需要将文件加载到 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名的子串。一个真正的功能会有些错误检查,以确保该模式实际上相匹配。
不隶属于 StackOverflow