Search code examples
lua

how to check if an input is a number


How do I check if an input is a number? My theory is like this:

local isNumber = tonumber(arg[1])

if isNumber then
print"This is sure a number"
else
print"This is not a number"
end

So, what you think?


Solution

  • arg[1] represents a number if tonumber(arg[1]) does not return nil. So this would for example also work for a string "1"

    If you want to make sure it is a number value check type(arg[1]) == "number"

    https://www.lua.org/manual/5.4/manual.html#pdf-tonumber

    https://www.lua.org/manual/5.4/manual.html#pdf-type