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

t.ok( isalpha( "abcABC" ) )

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

res, pos = isalpha( "abc123ABC" )
t.nok( res )
t.is( 4, pos )

res, pos = isalpha( "abcABC-123" )
t.nok( res )
t.is( 7, pos )

t.done()

Inspired by

See also