Search code examples
androidluacoronasdk

How does one edit a specific line of text in a file through lua?


I'm making an app in the Corona SDK that reads a .txt file from an SD card, presents the data in a cleaner form, then allows you to edit it. Some example text:

#207 USER PREFERENCES Time Between Pressure Log Samples
207=15
#208 USER PREFERENCES Auto Print Each Pressure Log Sample
208=No
#209 USER PREFERENCES Auto Print Each Event Log Entry
209=No
#210 USER PREFERENCES Selective Range Printing
210=1

Basically I need to be able to take a specific line of text from a file, edit it, and put it back in place, with pure Lua. For example, I might want to change 208=No to 208=Yes without changing anything else in the file.

I've already searched this site, Google, and Corona's API page, but nothing seems to have what I'm looking for. Am I going to have to read all the file up to that line and after that line and concatenate it all?


Solution

  • Am I going to have to read all the file up to that line and after that line and concatenate it all?

    You don't have to concatenate it. Just keep reading the file and storing lines until you reach the line you want to change. Make your change, read the entire rest of the file as one string, and then write all the previously read lines in order.

    It would look something like this:

    local hFile = io.open(..., "r") --Reading.
    local lines = {}
    local restOfFile
    local lineCt = 1
    for line in hFile:lines() do
      if(lineCt == ...) then --Is this the line to modify?
        lines[#lines + 1] = ModifyLine(line) --Change old line into new line.
        restOfFile = hFile:read("*a")
        break
      else
        lineCt = lineCt + 1
        lines[#lines + 1] = line
      end
    end
    hFile:close()
    
    hFile = io.open(..., "w") --write the file.
    for i, line in ipairs(lines) do
      hFile:write(line, "\n")
    end
    hFile:write(restOfFile)
    hFile:close()