0

我正在记录我通过 MPV 播放的视频文件,并且在使用 io 时我希望它为每个视频创建一行。使用初始选项它会删除它,并且在转到下一个视频时,默认情况下它不会添加新行。

我认为脚本应该接近工作。但是,这个问题挡住了我的路:“'(for generator)' 的错误参数 #1(无效选项)。显然,for 循环有问题,但我无法查明它,希望能有双手解决这个问题,因为我还在学习lua。

这是到目前为止的代码:

    if not paused then totaltime = totaltime + os.clock() - lasttime end
    message = (totaltime .. "s, " .. timeloaded .. ", " .. filename)
    local file = io.open(logpath, "r+")
    local lines = {}
    if file_exists(logpath) then
        for l in file:lines('L') do 
            if not l:find(message, 1, true) then
                lines[#lines+1] = 1
                file.write(message)
                file:close()
         end
     end
   end
end
4

1 回答 1

0

问题是这条线

for l in file:lines('L') do 

您可能正在运行 Lua 5.1,它不支持file:lines的选项 'L'

只需使用

for l in file:lines() do 

此外,如果您在通用 for 循环中关闭文件,则尝试从已关闭的文件中读取会导致错误。您应该在关闭文件后中断循环。

它说要写的参数不好(预期的文件*,得到字符串)。

替换file.write(message)file:write(message)的缩写file.write(file, message)。这个函数实际上需要两个参数。一是使用冒号语法时隐式提供的文件本身。

如果您只想在现有文件中添加一行,则无需阅读和检查所有行。只需使用选项“a”打开文件即可以附加模式打开它。

local file = io.open(logpath, "a")
if file then
   file:write("\nThis is a new line")
   file:close()
end
于 2022-02-09T09:45:45.687 回答