Testing if a variable has either numbers or letters or both/none LUA

563 Views Asked by At

Im trying to find out how to check in lua if a string variable has any letters in it, or numbers, like so:

myAwesomeVar = "hi there crazicrafter1"

if myAwesomeVar(has letters and numbers) then
    print("It has letters and numbers!")
elseif myAwesomeVar(has letters and not numbers) then
    print("It has letters!, but no numbers...")
elseif myAwesomeVar(has not letters and not numbers) then
    print("It doesnt have letters or numbers...")
elseif myAwesomeVar(has not letters and numbers) then
    print("It doesnt have letters, but it has numbers!")
end

I know some arguments of this are incorrect, but this is the kind of thing im aiming for my code to output:

It has letters and numbers!

1

There are 1 best solutions below

0
On

As Egor suggested you would write a functions that check if a string contains any digit or any letter...

Lua provides string patterns for convenient string analysis.

function containsDigit(str)

  return string.find(str, "%d") and true or false

end

I bet you can do the same for letters. Refer to Lua 5.3 Reference Manual 6.4.1: String patterns

The you can do something like

local myString = "hello123"
if containsDigit(myString) and containsDigit(myString) then
  print("contains both")
end