文件输入/输出模型;结合模式和在函数外定义文件参数:会导致崩溃。

local file_path = "Test.lua"
local file = io.open(file_path, "r")
local content = file:read("*a")
file:close() -- close the file after reading

local function replace(string_id, value)
    local string_id_search = tostring(string_id)
    local string_id_reconfiguration = tostring(value)
    local output = string.gsub(content, string_id_search, string_id_reconfiguration)
    local file = io.open(file_path, "w") -- open the file in write mode here
    file:write(output)
    file:close()
end

replace("string_id_to_replace", "new_value") -- call the function with test values

这是目前的代码。我在其他几个函数中也有这个重复的操作,我想优化它。所以我想先将函数的前三个局部变量去除,并使整个脚本具有这些局部变量。其次,我想将局部变量 file 合并成一个。

问题 1) 如果我将前三个局部变量去除,它会崩溃,说 file:write(output) 行试图写入一个已关闭的文件。

问题 2) 如果我将文件模式改为 "rw""wr",它也会崩溃。我尝试了所有其他模式,并得到了以下结果...

r 什么也没做(显然没有写入所需的数据)
w 摧毁文件中的所有数据(什么也没有写入)
a 什么也没做
r+ 什么也没做
w+ 摧毁一切
a+ 什么也没做

我是在模式上做错了什么,还是它们不能组合在一起?

点赞