WARNING!! Using tonumber on a client-input string is dangerous!

don’t forget about -inf

What’s with it? It’s just smaller than any other number. Can be protected against by simple “a < 0” check that you most likely already have. Even without a special case in tonumber fixer it most likely won’t cause problems.

it’s not limited to people checking if it’s above zero or not… sometimes they input negative numbers.

[editline]a[/editline]

*on purpose

[editline]b[/editline]

on second thought you should really just use the IsFinite function on the return, the following work in tonumber:



] m> tonumber"nan", tonumber"inf", tonumber"-nan", tonumber"-inf", tonumber"+nan", tonumber"+inf"
nan	inf	nan	-inf	nan	inf	


[editline]c[/editline]



] m> tonumber"1e100000000"
inf	


inf is not a problem. It adheres to the most important mathematical rules like the infinitely good little boy it is.

This is what I use.

Function



function isValidNumber( number )
	number = tonumber(number)

	if ( number != number ) then	
		return false
	end

	if( !number || !isnumber(number) || number <= 0 ) then
		return false
	end

	if ( number == math.huge || number == -math.huge) then
		return false
	end

	return true	
end


Test



concommand.Add("nanTest", function()
	print( _VERSION )

	print(isValidNumber(1/0))
	print(isValidNumber(-1/0))
	print(isValidNumber((1/0)/(1/0)))
	print(isValidNumber((0/0)/(0/0)))
	print(isValidNumber(0/0))

	print(isValidNumber(10))
	print(isValidNumber(45))
	print(isValidNumber(45))
end)	


Results



] nanTest 
Lua 5.1
false
false
false
false
false
true
true
true