Hey, is there any way to save/load information.
Going to need some way of saving progress
Yes, you can use sys.load() and sys.save() to load and save a Lua table. See http://doc.defold.com/ref/sys#sys.load for more information.
As a sidenote to @sicher’s answer I can also add that if the limitations of sys.save() get in the way you can also use the standard io functions to save files of any size (for instance caching of downloaded images or large json blobs). Combine this with sys.get_save_file() to get a platform independent file location to feed into the io functions.
Thanks for the replays. sys.save should work sence I built it so I only need to save some numbers.
Allthought I am trying to get the exampel to work but It can’t ever find the saved file…
I have copied the exempels and save the game during runtime (without error message so the file should exist)
But it will never find the file when I start the game the second time.
Do I need to setup anything else for this to work?
I think the example might be wrong here. What does load return? Can you do a pprint() and see if you in fact get the object read back?
This is the code I’m using:
local my_file_path = sys.get_save_file(“my_game”, “my_file”)
local my_table = sys.load(my_file_path)
pprint(sys.load(my_file_path))
if #my_table == 0 then
print(“Didn’t work”)
end
pprint writes:
DEBUG:SCRIPT:
{
my_key = my_important_value,
}
But the table will allways have the size 0 and return print(“Didn’t work”)
Yes, the documentation is wrong here. The problem is that the table is not treated as an array. If you do the following:
local my_table = {}
table.insert(my_table, "my_value")
local file_name = sys.get_save_file("my_app", "my_file")
if not sys.save(file_name, my_table) then
-- The file could not be saved!
end
Then the table will contain:
pprint(my_table)
DEBUG:SCRIPT:
{
1 = my_value,
}
And #my_table will be 1.
If you save arbitrary keys in the table, you will need to iterate with pairs():
local c = 0
for i, v in pairs(my_table) do
c = c + 1
end
if c == 0 then
-- no data in table
end
You can also make sure to write a specific key (“save_exists” for instance) when you save and check if that key exist to avoid the iteration.
As @sicher said, a Lua table with only non integer keys (ie not an array but a map/dictionary) will always have a #size of 0. If you want to check if a table is empty it’s better to do:
if not next(my_table) then
print("It's empty")
end
Nice! I’m learning something new!
Thanks for the feedback guys, got my save/load to work now =)
To bad that the documentation is wrong thou, someone should fix it.
Yes, it’s been fixed in our repo. Will push out the changes next release.