Search code examples
luanumbersdoubleequality

How safe is comparing numbers in lua with equality operator?


In my engine I have a Lua VM for scripting. In the scripts, I write things like:

stage = stage + 1
if (stage == 5) then ... end

and

objnum = tonumber("5")
if (stage == objnum)

According to the Lua sources, Lua uses a simple equality operator when comparing doubles, the internal number type it uses.

I am aware of precision problems when dealing with floating point values, so I want to know if the comparison is safe, that is, will there be any problems with simply comparing these numbers using Lua's default '==' operation? If so, are there any countermeasures I can employ to make sure 1+2 always compares as equal to 3? Will converting the values to strings work?


Solution

  • I can employ to make sure 1+2 always compares as equal to 3?

    You needn't worry. The number type in Lua is double, which can hold many more integers exactly than a long int.