lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 29/11/2019 00.20, D Burgess wrote:
Does that mean we get a "tointeger()" function in Lua?

There already is `math.tointeger`, which is happy to eat strings (both
in 5.3 and the current 5.4 development state).

Lua 5.4.0(git-6f1c033d)  Copyright (C) 1994-2019 Lua.org, PUC-Rio
math.tointeger( 1.0 )
1
math.tointeger( "1.0" )
1
math.tointeger( "0x1234" )
4660
math.tointeger( "0x1234p-2" )
1165
math.tointeger( "0x1234p-3" )
nil

Besides, tonumber() picks the right format.  (I.e., if it looks floaty
or is too big to fit in an integer, you'll get a float.  Otherwise,
you'll get an int.)  And on top of that, functions silently coerce
compatible values across subtypes – so even if you get the wrong
subtype, there won't be a problem – which means in practice you can just
use tonumber().

Lua 5.4.0(git-6f1c033d)  Copyright (C) 1994-2019 Lua.org, PUC-Rio
function test(v) local n = tonumber(v) ; return n, math.type(n) end test "9223372036854775807"
9223372036854775807	integer
test "9223372036854775808"
9.2233720368548e+18	float
test "1"
1	integer
test "1.0"
1.0	float
tonumber "1.0" ~ 3
2
tonumber "0"
0
math.cos( tonumber "0" )
1.0
("%d"):format( 1.0 )
1
("%.2f"):format( 1 )
1.00
("%d"):format( 1.2 )
stdin:1: bad argument #1 to 'format' (number has no integer representation)
stack traceback:
	[C]: in function 'string.format'
	stdin:1: in main chunk
	[C]: in ?

-- nobody