isdigit

function isdigit( str ) --> res, idx

Description

Checks if all characters in the string are decimal digits and there is at least one character. Decimal digits are any of: 0 1 2 3 4 5 6 7 8 9

Parameters

str

The string that should be checked.

Return Values

res

true if all characters in the string are decimal digits and there is at least one character, otherwise false.

idx

If res is false shows idx the first character that is not a decimal digit.

Code

--ZFUNC-isdigit-v1
local function isdigit( str ) --> res, idx
   local n = #str
   if n == 0 then return false, 0 end

   local b0, b9 = string.byte( "09", 1, 2 )
   for idx = 1, n do
      local b = string.byte( str:sub( idx, idx ) )
      if b < b0 or b > b9 then
         return false, idx
      end
   end

   return true
end

return isdigit

Examples

local t = require( "taptest" )
local isdigit = require( "isdigit" )

t( isdigit( "0123456789" ), true )

res, pos = isdigit( "" )
t( res, false )
t( pos, 0 )

res, pos = isdigit( "01234v6789" )
t( res, false )
t( pos, 6 )

t()

See also