Lua - line number behavior

I would like to know how Lua handles a number to convert strings using the tostring() function.

Is it going to convert to int (as a string) if the number is rounded (i.e. if number == (int) number ) or will it always output the real one (like a string), for example 10.0 ?

I need to map the exact behavior of Lua tostring in C without using the Lua C API, since in this case I am not using lua_State .

+5
source share
4 answers

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

In Lua 5.3, this has changed:

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

This is because Lua 5.3 introduced an integer subtype. From Changes in language :

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

+11
source

Lua converts numbers as:

 print(tostring(10)) => "10" print(tostring(10.0)) => "10.0" print(tostring(10.1)) => "10.1" 

If you want to play with them, there is a small online parser for simple commands, such as: http://www.lua.org/cgi-bin/demo This uses Lua 5.3.1

edit I have to support Yegorโ€™s comment, it depends on the version. I ran this locally on my system:

 Lua 5.2.4 Copyright (C) 1994-2015 Lua.org, PUC-Rio > print(tostring(10)) 10 > print(tostring(10.0)) 10 
+2
source

If you are using 5.3.4 and you need a quick fix, use math.floor - it translates it to int-number. This beats @warspyking's answer in efficiency, but lacks the coolness, which is bundles of code.

 >tostring(math.floor(54.0)) 54 >tostring(54.0) 54.0 
+1
source

In Lua 5.3, because of the integer type tostring on a float (although this numeric value may be equivalent to an integer) it will add the suffix "'.0' , but that does not mean that you cannot shorten it!

 local str = tostring(n) if str:sub(-2) == ".0" then str = str:sub(1,-3) end 
0
source

Source: https://habr.com/ru/post/1245143/


All Articles