0

I am logging video files I have played through MPV and while using io I want it to create one line per video. Using the inital options it merley deletes it, and upon going to next video, it won't add new line by default.

I think the script should be close to working. However, this issue stands in my way: "bad argument #1 to '(for generator)' (invalid option). Apparently, something is wrong with the for loop, but I am unable to pinpoint it and would appreciate a pair of hands in solving this problem as I am still learning lua.

Here's the code so far:

    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
Kayi
  • 11
  • 3

1 Answers1

0

The problem is this line

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

You're probably running Lua 5.1 which does not support that option 'L' for file:lines

Just use

for l in file:lines() do 

Also if you close the file in the generic for loop you'll cause an error for attempting to read from an already closed file. You should break the loop after closing the file.

It says bad argument to write (FILE* expected, got string).

Replace file.write(message) with file:write(message) which is short for file.write(file, message). This function actually needs two arguments. One is the file itself which is implicitly provided when using the colon syntax.

If you just want to add a line to an existing file you don't need to read and check all the lines. Just open the file with option 'a' to open it in append mode.

local file = io.open(logpath, "a")
if file then
   file:write("\nThis is a new line")
   file:close()
end
Piglet
  • 27,501
  • 3
  • 20
  • 43
  • Ah, thank you. Now it reads line 68 but got another problem on line 71. It says bad argument to write (FILE* expected, got string). I already moved the file:close out of for loop as you described. – Kayi Feb 09 '22 at 09:50
  • I am doing it this way since I want it to add one line per video. This way it only keeps adding lines and other options will only affect that same line. Even if I got the next video, it will merely replace or affect the single line in .txt file. – Kayi Feb 09 '22 at 09:54
  • I extended my answer regarding your second error. – Piglet Feb 09 '22 at 10:06
  • Thank you, but it still won't work. Haha, this is driving me nuts. Now it says no error on line 68 for some reason. – Kayi Feb 09 '22 at 10:14
  • maybe ask a new question with updated code and add mark which line is 68 – Piglet Feb 09 '22 at 10:20