阅读Lua中的特定行。

我正在寻找一种最简单的方法来读取一个位于文件中具有可变数量行数的字符串:

用户名=字符串在这里

我考虑过硬编码行号,但这不起作用,因为在这个文件中,用户名可能不止一次出现,而且行号不相同(从一个用户到另一个用户可能会改变)。

点赞
用户3204551
用户3204551
  1. 逐行读取文件
  2. 匹配行并提取用户名
  3. 将其放入一个列表中
function getusers(file)
    local list, close = {}
    if type(file) == "string" then
        file, close = io.open(file, "r"), true
    end
    for line in file:lines() do
        local user, value = line:match "^([^=]+)=([^\n]*)$"
        if user then -- 剔除格式不正确的行
            table.insert(list, user)
            list[user] = value -- 也可能有用,所以保存下来
        end
    end
    if close then
        file:close()
    end
    return list
end

可以使用文件或文件名调用此函数。

2014-10-01 19:04:19
用户3714446
用户3714446

我稍微编辑了上面的函数,现在它基本可以工作了,只需要编辑正则表达式。

function getusers(file)
local list, close = {}
    local user, value = string.match(file,"(UserName=)(.*)")
    print(value)
    f:close()
end
2014-10-02 08:00:14