I am writing a tiny RPG game, and I followed a tutorial to save my table.
But perhaps my English and coding ability are not good enough to understand the tutorial well.
I can’t save nor load data.
Please somebody corrects my code. Thank you very much.
here is website of the tutorial :
and the following is my code. I want to save and load HP and coin.
local user = {HP = 300, coin = 0}
function save(filename, userValue)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local file = io.open(path, “w”)
if file then
local contents = json.encode(userValue)
file:write( contents )
io.close( file )
end
end
function load(filename)
local path = system.pathForFile( filename, system.DocumentsDirectory)
local contents = “”
local userValue = {}
local file = io.open( path, “r” )
if file then
local contents = file:read( “*a” )
userValue = json.decode(contents);
io.close( file )
else
userValue.HP = 300
userValue.coin = 0
save(userValue, “userValue.json”)
end
end
user = load(“user.json”)
print(user.HP)
print(user.coin)