Corona SDK模拟器上的数据存储

我是 Corona SDK 的新手,正在尝试找到一种在模拟器上加载和保存文件(存储游戏数据的文件)的方法。(我不想在实际设备上进行调试,并且每次更改变量都需要花费15秒钟。)

我遵循了这里的教程:http://www.coronalabs.com/blog/2011/08/03/tutorial-exploring-json-usage-in-corona/ ,但在 stackoverflow 上没有找到已经解决这个问题的内容。

现在,我有以下用于读取和存储文件的代码:

local readJSONFile = function( filename, base )

    -- 如果没有指定基本目录,则设置默认的基本目录
    if not base then base = system.ResourceDirectory; end

    -- 为 Corona I/O 创建一个文件路径
    local path = system.pathForFile( filename, base )

    -- 将文件内容存储在 contents 中
    local contents

    -- io.open 打开路径中的文件,如果没有找到文件则返回nil
    local file = io.open( path, "r" )
    if file then
       -- 将文件中所有内容读取到字符串中
       contents = file:read( "*a" )
       io.close( file ) -- 使用后关闭文件
    end

    return contents
end

local writeToFile = function( filename, content )
    -- 如果没有指定基本目录,则设置默认的基本目录
    if not base then base = system.ResourceDirectory; end

    -- 为 Corona I/O 创建一个文件路径
    local path = system.pathForFile( filename, base )

    -- io.open 打开路径中的文件,如果没有找到文件则返回nil
    local file = io.open( path, "w" )
    if file then
       -- 将所有文件内容写入字符串中
       file:write( content )
       io.close( file ) -- 使用后关闭文件
    end
end

它“似乎”有效,因为我将读取到的 JSON 文件保存为不同的数据,然后加载它,似乎会持续存在。但是,一旦我关闭了我的 IDE,更改就会消失。此外,我在我的实际系统中(MacBook Pro)的文件实际上没有更改。

如果我这样做:

local json = require "json"
local wordsData = json.decode( readJSONFile( "trivia.txt" ) )
wordsData.someKey = "something different"
writeToFile("trivia.txt", json.encode( wordsData ) )  -- 这只是暂时生效

我正在读取与 main.lua 相同目录中的 trivia.txt 文件,然后尝试更改和加载内容。但是,上述代码不会对我的 MacBook Pro 上的 trivia.txt 进行实际更改。

应该如何正确实现这个? 我需要存储游戏设置和游戏数据(这是一个问答应用程序,我需要存储高达 50 个单词及用户选择的答案)。我需要以这样的方式存储数据,即当我关闭我的 IDE 时,它会记住我写入文件的内容。

我猜想当我加载 trivia.txt 时,它实际上正在查找我的 MacBook Pro 上的该文件,每次启动我的 IDE 时也一样。然后,当我第一次在模拟器上运行它时,它会在某个临时文件夹中创建一个新的 trivia.txt(我不知道它在哪里)。然后如果我再次运行相同的代码,它将从那里开始读取,对吗?

非常感谢您的任何帮助!!因为我是 Corona SDK 的新手,所以得到更详细的答案会有额外的赞赏。

点赞
用户2186639
用户2186639

我建议您使用 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
2013-05-20 06:39:14