Why must I use tonumber() only sometimes?

In this sample code:

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  

Since Lua is dynamically typed I can do this on line 5:

livesLeft.text = livesLeft.text - 1

…and treat the string as a number. But look at the line right above that, line 4 – when I tried to do this:

if event.phase == "began" and tonumber(livesLeft.text) \> 0 then

… I ended up having to use tonumber() to get things to work.

Why was I able to treat livesLeft.text as a number in one place, but had to cast it as a number in the other?

Is it because line 4 is a logical operation and line 5 is a mathematical operation? I guess I could understand that, except if Lua is dynamically typed and I’m using a number on the right side of the logical operation, shouldn’t the left side dynamically change to a number?

Jay
[import]uid: 9440 topic_id: 7173 reply_id: 307173[/import]

“>” 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.
[import]uid: 8093 topic_id: 7173 reply_id: 25244[/import]

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. :slight_smile:

Jay
[import]uid: 9440 topic_id: 7173 reply_id: 25248[/import]