-
Posted by brandon on Sat, 19 Jul 2008 17:37:12
I did the following:
> x=17
> print (type(17))
number
> x= tostring (x)
> print (type(x))
string
Next I did:>print (x+2)And i got:>19(shouldn't this be impossible???) because strings can't be added -
Posted by morlando on Mon, 14 Jul 2008 13:58:26
Just like how numbers are converted to strings when you concatenate (e.g.
print("Number: " .. 4)
), strings are converted to numbers when you do arithmetic (the example you've just discovered). I'm not as familiar with the material in Part I, so I can't say for sure where/if that's covered. -
Posted by jnwhiteh on Mon, 14 Jul 2008 21:36:12
In Lua numbers and strings are coerced when necessary (this is a somewhat confusing feature to new users, and shouldn't ever be counted on). There are mainly two places where this happens:
> 14 + "2"
16
> print("Fourteen: " .. 14)
Fourteen: 14Even then, it's best not to count on it (in the first example, you should use the number
2
and in the second example you should really usetostring()
orstring.format("Fourteen: %d", 14)
. -
Posted by brandon on Sat, 19 Jul 2008 17:37:12
So lua converts the string right back to a number automatically due to my arthimetic? I guess sooner or later the book will clear that up for me.
Thanks!