Lua check if a string is a decimal integer

Viewed 5298

How do I determine whether a string is an integer in lua? For example isInteger("123"), should be true. And isIntger("abc") and isIntger("12.3") should be false.

2 Answers

Starting with Lua 5.2 you can use tonumber to accomplish that. If you put second argument in it, the string will be treated as a number that should be an integer in base:

print(tonumber("145.5", 10)) -- nil
print(tonumber("145", 10)) -- 145
print(tonumber("-145", 10)) -- -145

In Lua 5.1 the situation is different as tonumber even with specified base accepts any number not only integers. I would probably use string.match:

print(("145.5"):match("^%-?%d+$")) -- nil
print(("145"):match("^%-?%d+$")) -- "145"
print(("-145"):match("^%-?%d+$")) -- "-145"

Patterns are described in section 5.4.1.

Having these values you can easily use them as booleans whenever needed, and also as actual integers when you need them. If you are looking for simpler strict boolean-only result, see Piglet's answer; it describes such intent better. I rarely run into such need, hence I suggest to use nil/value alternatives. It's a commonly used approach in Lua.

You could simply search for anything that is not a digit.

local function isInteger(str)

  return not (str == "" or str:find("%D"))  -- str:match("%D") also works

end
Related