Could use an example of writing and reading a file to variable.

I have been working on having my game track the top 5 high scores. It works great on iOS but most of the time it goes back to the home screen on Android. I am thinking maybe there is a better way to do what I am doing.

Right now I have it read and write to a separate file for each variable. So there is a file for all 5 names and all 5 scores. I would like to have a file that contains just the name and score for each player.

example: John Does 12500

Here is some code I was messing with.

local path = system.pathForFile( “name1.txt”, system.DocumentsDirectory )
local file = io.open( path, “r” )
if file then
local data = file:read("*a")
player1=data
io.close( file )
else
file = io.open( path, “w” )
file:write( player1, " “,highscore1,”\n" )
io.close( file )
end

The part with file:write( player1, " “,highscore1,”\n" ) works as far as writing 2 variables into the file, but I do not know how I could read them when needed and have it put the contents back into those variable.

Any help would be much appreciated. A little tough learning a new language and new APIs at the same time, but I have learned a lot in the last month.

Thanks in advance. [import]uid: 8533 topic_id: 5528 reply_id: 305528[/import]

If you use the JSON code that is available from here - http://www.chipmunkav.com/downloads/Json.lua - then you can save out a whole table really easily:

function saveOutTable(path, table)  
  
  
  
 local path = system.pathForFile( path, system.DocumentsDirectory )  
  
 file = io.open( path, "w" )  
 file:write( Json.Encode(table) )  
 io.close( file )  
  
  
end  

And then read it back in again:

function readInTable(path, baseDirectory)  
  
  
 local path = system.pathForFile( path, baseDirectory or system.DocumentsDirectory )  
  
 file = io.open( path, "r" )  
  
 if file then  
  
 local table = Json.Decode( file:read( "\*a" ) )   
  
 io.close( file )  
  
 return table  
  
 else  
 return nil  
 end  
end  

Hope that helps. [import]uid: 5833 topic_id: 5528 reply_id: 18749[/import]

Brilliant! :slight_smile: [import]uid: 9659 topic_id: 5528 reply_id: 18758[/import]

No problem, glad I could help. [import]uid: 5833 topic_id: 5528 reply_id: 18795[/import]

  • Edit -

Damn forum, double post. [import]uid: 5833 topic_id: 5528 reply_id: 18796[/import]

Looks like I got things working now. Thanks so much for your help. [import]uid: 8533 topic_id: 5528 reply_id: 18819[/import]