Why must I use tonumber() only sometimes?

In this sample code:

1
2
3
4
5
6
7
local livesLeft = display.newText(  "3", centerX, centerY, native.systemFont, 24 )
 
local screenTapped = function(event)
        if event.phase == "began" and tonumber(livesLeft.text) > 0 then
                livesLeft.text = livesLeft.text - 1
        end
end

">" is an operator that is both defined for numbers as well as for strings,

while "-" is defined only for numbers and not for strings

that's why the Lua runtime is able to cast the string correctly for "+-*/", but needs your help to do the right thing with ">"

I would recommend that you always explicitly cast to avoid surprises, even when Lua seems to do the right thing, and be very happy that you didn't find out the hard way when you think Lua "seems" to cast correctly but in actuality didn't cast at all:

"3" > "2" => true
"+3" > "2" => false
"-3" > "2" => false
"-3" > "-2" => true

Ouch...
-FrankS.

Thanks, FrankS, that makes sense.

A little while after I posted that I was skimming through Programming in Lua (which was just delivered from Amazon today) and saw where they say they're not sure automatic coercions are a good idea -- and at that point decided using tonumber() was probably a good habit to get into.

Thanks for validating that guess for me. :)

Jay

views:1329 update:2011/10/6 9:28:12
corona forums © 2003-2011