【发布时间】:2013-05-14 13:17:35
【问题描述】:
Corona SDK 的新手,我正在尝试找出一种在模拟器上加载和保存文件(存储游戏数据)的方法。 (我不想在真实设备上调试,每次都花 15 秒来查看变量的变化)。
我按照此处的教程进行操作:http://www.coronalabs.com/blog/2011/08/03/tutorial-exploring-json-usage-in-corona/,但在 stackoverflow 上找不到任何已解决此问题的内容。
现在我有以下代码用于读取和存储文件:
local readJSONFile = function( filename, base )
-- set default base dir if none specified
if not base then base = system.ResourceDirectory; end
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
-- will hold contents of file
local contents
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
contents = file:read( "*a" )
io.close( file ) -- close the file after using it
end
return contents
end
local writeToFile = function( filename, content )
-- set default base dir if none specified
if not base then base = system.ResourceDirectory; end
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "w" )
if file then
-- write all contents of file into a string
file:write( content )
io.close( file ) -- close the file after using it
end
end
它似乎可以工作,因为我会读取我的 JSON 文件,用不同的数据保存它,加载它,这似乎会持续存在。但是,一旦我关闭我的 IDE,更改就消失了。此外,我系统(mac book pro)上的实际文件没有改变。
如果我这样做:
local json = require "json"
local wordsData = json.decode( readJSONFile( "trivia.txt" ) )
wordsData.someKey = "something different"
writeToFile("trivia.txt", json.encode( wordsData ) ) -- this only works temporarily
我正在阅读我的trivia.txt 文件,该文件与我的main.lua 位于同一目录中,并尝试更改和加载某些内容。但是,上面的代码不会对我的 mac book pro 上的trivia.txt 进行实际更改。
这样做的正确方法是什么??我需要存储游戏设置和游戏数据(这是一个琐事应用程序,我需要存储最多 50 个单词以及用户选择的答案) .我需要以这样的方式存储数据,当我关闭我的 IDE 时,它会记住我写入文件的内容。
我的猜测是,当我加载我的trivia.txt 时,它实际上是在每次加载我的 IDE 时查看我的 mac book pro 中的那个文件。但是当我第一次在我的模拟器上运行它时,它会在一些临时文件夹中创建一个新的trivia.txt(我不知道它在哪里)。然后如果我重新运行相同的代码,它将从那里开始读取。对吧?
任何帮助将不胜感激!!!赞成更详细的答案,因为我是 Corona SDK 的新手
【问题讨论】:
标签: mobile lua persistence coronasdk