如何在Corona中实现与"NSUserDefaults"相当的功能?

我想要做的只是保存我的用户(玩家)高分,并让这些信息在 Corona SDK(Lua)应用程序(游戏)重新启动时持久存在。我希望在 iOS 和 Android 上都可以良好地运行。我的高分数据实际上是两个包含数字的 Lua 表格。

正确且最简单的方法是什么?

原文链接 https://stackoverflow.com/questions/9301091

点赞
stackoverflow用户909233
stackoverflow用户909233

你可以将分数保存到一个表中,然后将其序列化成json格式的文本文件。

local json=require("json")
local savefile="scores.json"

scores=
    {
        {
            level=1,
            status=0,
            highscore=0,
        },
        {
            level=2,
            status=0,
            highscore=0,
        },
    }

function getScore(filename, base)
    -- 如果没有指定路径,则设置默认路径
    if not base then
        base = system.DocumentsDirectory
    end

    -- 创建corona i/o文件路径
    local path = system.pathForFile(filename, base)

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

    -- io.open在给定路径处打开一个文件。如果没有找到文件,则返回nil
    local file = io.open(path, "r")
        local scores
    if file then
        -- 将文件的所有内容读入字符串中
        contents = file:read( "*a" )
            if content ~= nil then
            scores=json.decode(content)
            end
        io.close(file) -- 使用后关闭文件
    end

    return scores
end

function saveScore(filename, base)
    -- 如果没有指定路径,则设置默认路径
    if not base then
        base = system.DocumentsDirectory
    end

    -- 创建corona i/o文件路径
    local path = system.pathForFile(filename, base)

    -- io.open在给定路径处打开一个文件。如果没有找到文件,则返回nil
    local file = io.open(path, "wb")
    if file then
        -- 将文件的所有内容写入字符串中
        file:write(json.encode(scores))
        io.close(file) -- 使用后关闭文件
    end
end

全局变量scores可以像普通表一样进行操作,当你想要加载或保存scores表时,你可以调用上面的函数。

2012-02-16 01:23:42