【问题标题】:How does one edit a specific line of text in a file through lua?如何通过 lua 编辑文件中的特定文本行?
【发布时间】:2012-03-09 20:25:44
【问题描述】:

我正在 Corona SDK 中制作一个应用程序,它从 SD 卡读取 .txt 文件,以更清晰的形式呈现数据,然后允许您对其进行编辑。 一些示例文本:

#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

基本上,我需要能够使用纯 Lua 从文件中获取特定的文本行,对其进行编辑,然后将其放回原处。例如,我可能想将208=No 更改为208=Yes,而不更改文件中的任何其他内容。

我已经搜索过这个网站、Google 和 Corona 的 API 页面,但似乎没有我想要的东西。我是否必须读取该行之前的所有文件以及该行之后的所有文件并将其全部连接起来?

【问题讨论】:

    标签: android lua coronasdk


    【解决方案1】:

    我是否必须读取该行之前和该行之后的所有文件并将其全部连接起来?

    您不必连接它。只需继续读取文件并存储行,直到到达要更改的行。进行更改,将文件的其余部分作为一个字符串读取,然后按顺序写入之前读取的所有行。

    看起来像这样:

    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()
    

    【讨论】:

    • 我希望有更优雅的东西,但如果这就是它所需要的,那就是它所需要的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多