【问题标题】:Read/Write highscore from a file (Lua - Corona SDK)从文件读取/写入高分(Lua - Corona SDK)
【发布时间】:2018-03-20 01:03:12
【问题描述】:

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

感谢您的帮助!

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 )

【问题讨论】:

  • 我发现使用 .json 保存分数/数据很容易。您可以使用 Rob Miracle 简单模块来加载和保存文件。

标签: file mobile lua coronasdk


【解决方案1】:

我自己也遇到过这个问题。我发现如果你在"w+"模式下打开一个文件,当前的内容会被删除,这样你就可以写入新的内容了。因此,要读取和写入,您必须打开文件两次。首先,您以"rb" 模式打开文件并获取文件内容,然后将其关闭。然后以"wb" 模式重新打开它,写入新号码,然后关闭它。

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

Lua 支持的文件模式是从 C 语言中借来的。 (我在第 305 页找到了我猜想是 a draft of the C specification 的描述。)我认为 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":文件的最后一个字节原始内容不会被删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 2015-01-17
    • 2018-04-29
    • 2012-05-08
    • 2011-06-20
    相关资源
    最近更新 更多