[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Just curious: Why is tonumber(nil) not 0?
- From: Luiz Henrique de Figueiredo <lhf@...>
- Date: Mon, 27 Apr 2009 10:52:51 -0300
> I was briefly caught by doing this test:
>
> if tonumber(something) > 0 then
> ...
> end
>
> with something=nil.
>
> I'm not advocating a change, but what's the thought-process behind this
> behavior? Wouldn't you consider the numeric value of nil to be 0?
The current behavior is useful to catch typos:
myNumber = "123.456"
print(tonumber(mynumber)) -- note typo
If you really need the numeric value of nil to be 0 just redefine tonumber:
do
local _tonumber=tonumber
function tonumber(x)
if x==nil then return 0 else return _tonumber(x) end
end
end
If tonumber supported a __tonumber metamethod, this could be simpler.