Lua – Number to string behaviour

cluatostring

I would like to know how Lua handles the number to string conversions using the tostring() function.

It is going to convert to an int (as string) if the number is round (i.e if number == (int) number) or is it always going to output a real (as string) like 10.0 ?

I need to mimic the exact behaviour of Lua's tostring in C, without using the Lua C API since, in this case, I'm not using a lua_State.

Best Answer

In Lua 5.2 or earlier, both tostring(10) and tostring(10.0) result as the string "10".

In Lua 5.3, this has changed:

print(tostring(10)) -- "10"
print(tostring(10.0)) -- "10.0"

That's because Lua 5.3 introduced the integer subtype. From Changes in the Language:

The conversion of a float to a string now adds a .0 suffix to the result if it looks like an integer. (For instance, the float 2.0 will be printed as 2.0, not as 2.) You should always use an explicit format when you need a specific format for numbers.

Related Topic