isxdigit

function isxdigit( str ) --> res, idx

Description

Checks if all characters in the string are hexdecimal digits and there is at least one character. Decimal digits are any of: 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E D

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 hexdecimal digit.

Code

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

   local b0, b9 = string.byte( "09", 1, 2 )
   local ba, bf = string.byte( "af", 1, 2 )
   local bA, bF = string.byte( "AF", 1, 2 )
   for idx = 1, n do
      local b = string.byte( str:sub( idx, idx ) )
      if b >= b0 and b <= b9 then
      elseif b >= ba and b <= bf then
      elseif b >= bA and b <= bF then
      else
         return false, idx
      end
   end

   return true
end

return isxdigit

Examples

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

t( isxdigit( "0123456789abcdefABCDEF" ), true )

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

res, pos = isxdigit( "abcdefghABCDEFGH" )
t( res, false )
t( pos, 7 )

res, pos = isxdigit( "ABCDEFGHabcdefgh" )
t( res, false )
t( pos, 7 )

t()

Inspired by

See also