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( "tapered" )
local isdigit = require( "isdigit" )

t.ok( isdigit( "0123456789" ) )

res, pos = isdigit( "" )
t.nok( res )
t.is( 0, pos )

res, pos = isdigit( "01234v6789" )
t.nok( res )
t.is( 6, pos )

t.done()

See also