isalpha

function isalpha( str ) --> res, idx

Description

Checks if all characters in the string are alphabetical ASCII character and there is at least one character.

Parameters

str

The string that should be checked.

Return Values

res

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

idx

If res is false shows idx the first character that is not a alphabetical ascii character.

Code

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

   local ba, bz = string.byte( "az", 1, 2 )
   local bA, bZ = string.byte( "AZ", 1, 2 )
   for idx = 1, n do
      local b = string.byte( str:sub( idx, idx ) )
      if b >= ba and b <= bz then
      elseif b >= bA and b <= bZ then
      else
         return false, idx
      end
   end

   return true
end

return isalpha

Examples

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

t( isalpha( "abcABC" ), true )

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

res, pos = isalpha( "abc123ABC" )
t( res, false )
t( pos, 4 )

res, pos = isalpha( "abcABC-123" )
t( res, false )
t( pos, 7 )

t()

Inspired by

See also