Different tonumber() behavior between 5.2 and 5.3

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Different tonumber() behavior between 5.2 and 5.3

Tony Papadimitriou
Here it is:
 
-----------
 
c:\temp>lua53 -E
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
Lua>tonumber(100,4)
stdin:1: bad argument #1 to 'tonumber' (string expected, got number)
stack traceback:
        [C]: in function 'tonumber'
        stdin:1: in main chunk
        [C]: in ?

c:\temp>lua52 -E
Lua 5.2.4  Copyright (C) 1994-2015 Lua.org, PUC-Rio
Lua>=tonumber(100,4)
16
-----------
 
The online manual for either case says that when base is present the number should be a string:
5.3: When called with base, then e must be a string to be interpreted as an integer numeral in that base.
5.2: When called with base, then e should be a string to be interpreted as an integer numeral in that base.
 
Although 5.3 conforms more strictly to the manual, 5.2’s flexibility is more practical -- avoids an extra tostring().
Is there a reason 5.3 lost this flexibility?  Could it get it back?
 
Reply | Threaded
Open this post in threaded view
|

Re: Different tonumber() behavior between 5.2 and 5.3

Roberto Ierusalimschy
> Is there a reason 5.3 lost this flexibility?

Automatic coercion from numbers to strings is already considered bad
by many people. Lua usually avoids this coercion when it can lead to
confusion (e.g., 10 == "10"). In this case, as your example shows,
it sounds quite weird:

> tonumber(100, 4)  --> 16

100 is already a number! "Converting" it to a number should not change
its value.

-- Roberto