Dav*_* T. 0 mobile lua persistence coronasdk
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
Run Code Online (Sandbox Code Playgroud)
它似乎工作,因为我会读取我的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
Run Code Online (Sandbox Code Playgroud)
我正在读取与我trivia.txt在同一目录中的文件,main.lua并尝试更改和加载某些内容.但是,上面的代码不会trivia.txt对我的mac book pro 进行实际更改 .
什么是正确的方法?我需要存储游戏设置和游戏数据(这是一个琐事应用程序,我需要存储多达50个单词以及用户选择的答案).我需要以这样的方式存储数据:当我关闭我的IDE时,它会记住我写入文件的内容.
我的猜测是,当我加载我trivia.txt的时候,每次加载我的IDE 时,它实际上都在查看我的mac book pro for the file.但是当我第一次在我的模拟器上运行它时,它会trivia.txt在一些临时文件夹中创建一个新文件(我不知道这是哪里).如果我重新运行相同的代码,它将从那里开始读取.对?
任何帮助将非常感激!!!由于我是Corona SDK的新用户,所以请求更详细的解答
我建议你使用system.DocumentsDirectory作为路径.首先,您可以从资源目录中读取,然后将其存储在DocumentsDirectory中.之后,您始终可以查找DocumentsDirectory.这将解决您的问题.这里有一些函数可以检查文件是否存在.您可以修改路径
function saveTable(t, filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local file = io.open(path, "w")
if file then
local contents = json.encode(t)
file:write( contents )
io.close( file )
return true
else
return false
end
end
function loadTable(filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local myTable = {}
local file = io.open( path, "r" )
local contents = ""
if file then
-- read all contents of file into a string
local contents = file:read( "*a" )
myTable = json.decode(contents);
io.close( file )
return myTable
end
return nil
end
Run Code Online (Sandbox Code Playgroud)