Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - Number to string behaviour

Tags:

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.

like image 716
Virus721 Avatar asked Mar 16 '16 09:03

Virus721


People also ask

How do I convert a number to a string in Lua?

String s=((Integer)i). toString(); Demo.

How do you typecast in Lua?

“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.

What is Tostring Lua?

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.

What does %s mean in Lua?

Lua uses %s in patterns (Lua's version of regular expressions) to mean "whitespace". %s+ means "one or more whitespace characters".


1 Answers

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.

like image 79
Yu Hao Avatar answered Oct 06 '22 13:10

Yu Hao