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
.
String s=((Integer)i). toString(); Demo.
“Type coercion” is the implicit or automatic conversion of a value from one type to another. In Lua, this is either from a string to a number or a number to a string. Lua will automatically convert the string and number types to the correct format in order to perform calculations.
Lua: Basic Functions: tostring. tostring (e) Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use string.
Lua uses %s in patterns (Lua's version of regular expressions) to mean "whitespace". %s+ means "one or more whitespace characters".
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 float2.0
will be printed as2.0
, not as2
.) You should always use an explicit format when you need a specific format for numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With