Lua中的string.find迭代

我目前正在Minecraft和OpenComputers游戏中的一个项目中工作。主要编程语言为Lua。

现在,我需要找到一种好的解决方案来迭代一个字符串。

我的当前解决方案如下:

local config = "key1=type1\nkey2=type2\nkey3=type3"
local lines = {}
while true do
    local length = config:len()
    local s, f = config:find("\n")
    if s ~= nil then
        table.insert(lines, config:sub(1, s-1))
        config = config:sub(f+1, length)
    else
        table.insert(lines, config)
        break
    end
end

在这个例子中,我有一个静态的字符串在变量config中,但在实际代码中,我会从配置文件中读取行。

我的解决方案有效,但我认为它可能更简洁。有没有更简洁的解决方案?

点赞
用户107090
用户107090

如果你想遍历文件中的每一行,可以使用 io.lines

local lines = {}
for l in io.lines("config.txt") do
    table.insert(lines, l)
end
2017-12-08 13:59:25