Как реализовать функциональность «NSUserDefaults» в Corona? - PullRequest
0 голосов
/ 16 февраля 2012

Все, что я хочу, это сохранить рекорды пользователей (игроков), и эта информация сохранится между запусками приложений (игр) в Corona SDK (Lua). Я хочу, чтобы он хорошо работал на iOS и Android. Мои рекордные данные на самом деле две таблицы lua, содержащие числа.

Какой правильный и самый простой способ сделать это?

1 Ответ

3 голосов
/ 16 февраля 2012

Вы можете сохранить результаты в таблице, а затем сериализовать их в текстовый файл в формате 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)
    -- set default base dir if none specified
    if not base then 
        base = system.DocumentsDirectory 
    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")
        local scores
    if file then
        -- read all contents of file into a string
        contents = file:read( "*a" )
            if content ~= nil then
            scores=json.decode(content)
            end
        io.close(file) -- close the file after using it
    end

    return scores
end

function saveScore(filename, base)
    -- set default base dir if none specified
    if not base then 
        base = system.DocumentsDirectory 
    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, "wb")
    if file then
        -- write all contents of file into a string
        file:write(json.encode(scores))
        io.close(file) -- close the file after using it
    end
end

Глобальной переменной scores можно манипулировать как обычной таблицей, и когда вы хотитеЗагрузите или сохраните таблицу scores, для которой вы можете вызвать указанные выше функции.

...