[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: tonumber() inconsistent behavior
- From: Dirk Laurie <dpl@...>
- Date: Tue, 26 Jul 2011 12:33:23 +0200
On Tue, Jul 26, 2011 at 02:46, Dirk Feytons <dirk.feytons@gmail.com> wrote:
> tonumber({}) returns nil
> tonumber({}, 16) throws an error
>
> Is there a specific reason why the behavior is different when a
> non-default base is given?
The manual says:
> Tries to convert its argument to a number. If the argument is already a
> number or a string convertible to a number, then tonumber returns this
> number; otherwise, it returns nil.
There is nothing about throwing an error. So the behaviour in the
case tonumber({}, 16) is an Implemented Non-Standard effECT
(let's avoid nasty words like "bug").
On Tue, Jul 26, 2011 at 10:52:18AM +0200, HyperHacker wrote:
> Hmm, this is also interesting:
> > n=99
> > print(tonumber(n,16))
> prints 153 (which is 0x99). It seems when you specify a base, it
> converts the value to a string and then interprets it as a number,
> even if it were already a number to begin with.
>
> I feel like tonumber() should just return the number it's given if it
> is in fact a number (no conversion is necessary), but I'm not sure
> what it should do about the base in that case.
The manual says:
> The base may be any integer between 2 and 36, inclusive. In bases above 10,
> the letter 'A' (in either upper or lower case) represents 10, 'B' represents
> 11, and so forth, with 'Z' representing 35. In base 10 (the default), the
> numeral is converted following the coercion rules (see §3.4.2). In other
> bases, only integers are accepted.
I'm happy to equate 1011011100101 with "1011011100101" for the purpose
of base conversion. Isn't that the meaning of the middle sentence?
Dirk