save and load game data

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Happy_G
Prole
Posts: 8
Joined: Wed Dec 31, 2008 6:33 am

save and load game data

Post by Happy_G »

im having trouble figuring out how to save and load game data like say saving what level someone is on as well as the number of lives they have and the items in thier posession and such, so just saving and loading specific variables or tables is what im trying to do
User avatar
Kaze
Party member
Posts: 189
Joined: Sat Jul 19, 2008 4:39 pm
Location: Dublin, Ireland

Re: save and load game data

Post by Kaze »

Something like this could work.

Code: Select all

function table.save( tab, filename )
	local f = love.filesystem.newFile( filename or "savedata.txt", love.file_write )
	love.filesystem.open( f )
	local data = ""
	for i, v in pairs( tab ) do
		data = data .. type(i) .. ";" .. i .. "=" .. type(v) .. ";" .. v .. "\n"
	end
	
	love.filesystem.write( f, data )
	love.filesystem.close( f )
end

function table.load( filename )
	if not love.filesystem.exists( filename or "savedata.txt" ) then return {}; end
	
	local tab = {}
	for line in love.filesystem.lines( filename or "savedata.txt" ) do
		local eqpos = (line:find( "=" ))
		
		
		local name = line:sub( 1, eqpos - 1 )
		
		local nbreakpos = (name:find( ";"))
		local nametype = name:sub( 1, nbreakpos - 1 )
		local namevalue = name:sub( nbreakpos + 1 )
		
		
		local data = line:sub( eqpos + 1 )
		
		local breakpos = (data:find( ";" ))
		local datatype = data:sub( 1, breakpos - 1 )
		local value = data:sub( breakpos + 1 )
		
		tab[_G["to" .. nametype]( namevalue )] = _G["to" .. datatype]( value )
	end
	
	return tab;
end
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 4 guests