我的问题是:我有一个带有高分的文件(只有第一行,没有昵称,只有高分),我需要阅读这一行,并将它与游戏会话中获得的实际分数进行比较,如果分数较高,则用新值覆盖文件,但如果我试图读取它,我将得到一个空值.看上去我看得不对。我的密码怎么了?
谢谢你的帮助!
local path = system.pathForFile( "data.sav", system.DocumentsDirectory )
local file = io.open( path, "w+" )
highscore_letta = file:read("*n")
print(highscore_letta)
if (_G.player_score > tonumber(highscore_letta)) then
file:write(_G.player_score)
end
io.close( file )发布于 2018-03-20 01:41:26
我自己也有这个问题。我发现,如果您在"w+"模式下打开一个文件,那么当前的内容就会被删除,以便您可以编写新的内容。因此,要读和写,你必须打开文件两次。首先,以"rb"模式打开文件并获取文件内容,然后关闭它。然后在"wb"模式下重新打开它,编写新的数字,然后关闭它。
在Windows中,您需要在文件模式下使用"b"。否则,您正在读取和写入的字符串可能会以意外的方式被修改:例如,换行符("\n")可能会被回车换行符("\r\n")所取代。
Lua支持的文件模式是从C语言中借用的。(我在第305页找到了一份我猜是C规范草案的描述。)我认为Lua手册假设您会知道这些模式意味着什么,就像一个经验丰富的C程序员所做的那样,但对我来说,这一点都不明显。
因此,读一个数字,然后写一个新的:
local filepath = "path/to/file"
-- Create a file handle that will allow you to read the current contents.
local read_file = io.open(filepath, "rb")
number = read_file:read "*n" -- Read one number. In Lua 5.3, use "n"; the asterisk is not needed.
read_file:close() -- Close the file handle.
local new_number = 0 -- Replace this with the number you actually want to write.
-- Create a file handle that allows you to write new contents to the file,
-- while deleting the current contents.
write_file = io.open(filepath, "wb")
write_file:write(new_number) -- Overwrite the entire contents of the file.
write_file:flush() -- Make sure the new contents are actually saved.
write_file:close() -- Close the file handle.我创建了一个脚本来自动执行这些操作,因为每次输入这些操作都有点烦人。
模式"r+"或"r+b"应该允许您读写,但是当原始内容比新内容更长时,我无法让它工作。如果原始内容是"abcd",四个字节,而新内容是"efg",三个字节,并且您在文件中写入偏移量0,那么文件现在将有"efgd":原始内容的最后一个字节未被删除。
https://stackoverflow.com/questions/49374824
复制相似问题