Persistence of data? (SOLVED)

I wanted to ask how to do you go about keep data persistent in defold?

For example saving level state, items etc.

In the past on iOS I used NSUserDefaults or just stored a JSON file on the filesystem then loaded this on init of the stage.

How do you go about this in defold / lua

Huge thanks :slight_smile:

1 Like

Hi @ianshk!

You can use our built in sys.save for storing data.

2 Likes

As @Mathias_Westerdahl suggested sys.save() and sys.load() will do the trick. Remember to use sys.get_save_file() to get a writable path to the file.

local some_data = { score = 12345, name = "Foobar" }

local filename = sys.get_save_file("myapp", "mysavefile")
local success = sys.save(filename, some_data)

local loaded_data = sys.load(filename)

Note that there is a limitation on the size of the table that you can persist using sys.save() and a limitation on the keys.

You can also use the io.* functions to store data in your own format or larger amounts of data:

local filename = sys.get_save_file("myapp", "mysavefile")
local file, error = io.open(filename, "wb")
if not file then
    print(error)
    return
end
file:write("somedata")
file:flush()
file:close()

local file, error = io.open(filename, "rb")
if not file then
    print(error)
    return
end
local somedata = file:read("*a")
7 Likes

Awesome thanks guys.

3 Likes