String to Number?

Hey…

I’m trying to give players in my game awards based on their scores, which are saved into JSON.

Problem is, JSON stores the scores as strings, not numbers, and I can’t compare a string to a number.

Is there a way to format a string into a number?

Lua has a tonumber function:

http://docs.coronalabs.com/api/library/global/tonumber.html

You should be able to store that number into an array, then encode that array into JSON. Later decode it back into a table with the number still inside.
 

local score = 10 local scoreTable = {score} local path = system.pathForFile( "scores", system.DocumentsDirectory ) local file = io.open( path, "w" ) if file then local contentsScores = json.encode( scoreTable ) file:write( contentsScores ) io.close( file ) end

And then decode it later

local path = system.pathForFile( "scores", system.DocumentsDirectory ) local file = io.open( path, "r" ) if file then local contents = file:read( "\*a" ) local savedScores = json.decode( contents ) score = savedOptions[1] io.close( file ) end

Just remember to nil out the path, file and contents variables between methods.

Lua has a tonumber function:

http://docs.coronalabs.com/api/library/global/tonumber.html

You should be able to store that number into an array, then encode that array into JSON. Later decode it back into a table with the number still inside.
 

local score = 10 local scoreTable = {score} local path = system.pathForFile( "scores", system.DocumentsDirectory ) local file = io.open( path, "w" ) if file then local contentsScores = json.encode( scoreTable ) file:write( contentsScores ) io.close( file ) end

And then decode it later

local path = system.pathForFile( "scores", system.DocumentsDirectory ) local file = io.open( path, "r" ) if file then local contents = file:read( "\*a" ) local savedScores = json.decode( contents ) score = savedOptions[1] io.close( file ) end

Just remember to nil out the path, file and contents variables between methods.