I made a simple script to write JSON data to a file, then read it after it has been written:
local json = require("json")
local filename = "save.json"
local path = system.pathForFile(filename, system.DocumentsDirectory)
local data = {
thing = 3,
otherthing = "whatup"
}
local function save()
local file, err = io.open(path, "w")
if file then
local json = json.encode(data, { indent = true })
file:write(json)
else
print("ERROR: " .. err)
end
end
local function load()
local file, err = io.open(path, "r")
if file then
local contents = file:read("*a")
print("Contents: " .. contents)
io.close(file)
end
end
save()
timer.performWithDelay(10000, load)
If I try to save this file and load it immediately afterwards without the timer, it will print an empty string. It turns out that after the file is written to, it stays empty for several seconds before the contents of the file appear and I can read it.
I tested this in the Corona Simulator. I’d assume the delay is smaller on a real device, but I’m concerned about edge cases where the player tries to read the data too early and thinks there is no data.
Is this the correct way to handle save data? If not, how do you do it?