从文件读取/写入高分(Lua - Corona SDK)

时间:2018-03-20 01:03:13

标签: file mobile lua corona

这是我的问题:我有一个写有高分的文件(只是第一行,没有昵称,只有高分),我需要阅读该行并将其与实际得分进行比较游戏会话,如果分数较高,用新值覆盖文件,但如果我尝试读取它,我得到一个空值...似乎我没有正确读取它。我的代码出了什么问题?

感谢您的帮助!

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 )

1 个答案:

答案 0 :(得分:0)

我自己有这个问题。我发现如果您以"w+"模式打开文件,则会删除当前内容,以便您可以编写新内容。所以要读写,你必须打开文件两次。首先,以"rb"模式打开文件并获取文件内容,然后将其关闭。然后以"wb"模式重新打开它,写下新号码并关闭它。

在Windows中,您需要在文件模式下使用"b"。否则,您正在读取和写入的字符串可能会以意外的方式进行修改:例如,换行符("\n")可能会被回车换行符("\r\n")替换。

Lua支持的文件模式是从C语言中借用的。 (我在第305页找到了一个描述,我猜是a draft of the C specification。)我认为Lua手册类型假设你会知道这些模式的意思,作为一个经验丰富的C程序员会,但对我来说它不是&# 39; t显而易见。

这样读取一个数字然后写一个新的数字:

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处写入,则文件现在将具有{{1 }:不删除原始内容的最后一个字节。