Very basic question about display.text() in API

Hi -

I understand this is not Lua related but I didn’t know where I should post this.
CODE:

a = math.random(10)

local total = display.newText (a + a, 100, 400, native.systemFont, 24 )
total:setTextColor (255, 255, 255)

RESULTS:

Results from a + a is displayed (18, for example, when I just ran it in the simulator)

QUESTION:

I put a math function (a+a) so why wasn’t there an error because you can’t “add” strings, right??

The first parameter in display.newText is a string:

display.newText( string, left, top, font, size )
Thanks in advance!

[import]uid: 45656 topic_id: 15170 reply_id: 315170[/import]

It’s called Coercion and Lua is nice enough to do this for you. The result of a + a is indeed a number and Lua converts it to a string for you.

You could also do something like this:

[lua]local a = 3
local b = “7”

print( a + b ) – Prints 10[/lua]

From the Lua manual:

Lua provides automatic conversion between string and number values at run time. Any arithmetic operation applied to a string tries to convert this string to a number, following the usual conversion rules. Conversely, whenever a number is used where a string is expected, the number is converted to a string, in a reasonable format. For complete control over how numbers are converted to strings, use the format function from the string library (see string.format). [import]uid: 5833 topic_id: 15170 reply_id: 56106[/import]

From the lua users strings tutorial:

http://lua-users.org/wiki/StringsTutorial

“Lua performs automatic conversion of numbers to strings and vice versa where it is appropriate. This is called coercion.”

I use variables hold numbers I’ve performed arithmetic on all the time.
–EDIT–

Looks like GrahamRanson just beat me to it…

“missed it by that much.” [import]uid: 64596 topic_id: 15170 reply_id: 56107[/import]

Thanks so much you two!

[import]uid: 45656 topic_id: 15170 reply_id: 56220[/import]