Gideros Mobile tutorial – Loading And Saving Data

You will often want to save important information such as the player’s name, score, high score, current location in the game and object positions. Here, we’ve created two copies of […]

You will often want to save important information such as the player’s name, score, high score, current location in the game and object positions.

local Player = "Jason"
local Score = 23980
local HiScore = 349870
local Player2 = nil
local Score2 = nil
local HiScore2 = nil
local file=io.open("|D|settings.txt","w+")
file:write(Player .. "\n")
file:write(Score .. "\n")
file:write(HiScore .. "\n")
file:close()
file2=io.open("|D|settings.txt", "r")
Player2=file2:read("*line")
Score2=tonumber(file2:read("*line"))
HiScore2=tonumber(file2:read("*line"))
file2:close()
print ("Player: ", Player2)
print ("Score: ", Score2)
print ("HiScore: ", HiScore2)

Here, we’ve created two copies of each variable and assigned ‘nil’ to the second version just to prove the variables were blank between saving and loading. Of course, you won’t be doing this in your actual application.

Initialise Your Data

An easy way to initialise your application settings is to first check if a save file exists with your values. If not, define default values for the application until the user changes this.

local Player
local Score
local HiScore
local file = io.open("|D|settings.txt","r")
if not file then
Player = "Nobody"
Score = 0
HiScore = 0
else
Player=file:read("*line")
Score=tonumber(file:read("*line"))
HiScore=tonumber(file:read("*line"))
file:close()
end

This way you will always have values for your application to use.

Tags:
Jason Oakley

About Jason Oakley