local pass = io.read()
local letters = {"A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"}
local numbers = {"1","2","3","4","5","6","7","8","9","0"}
local symbols = {">","!","&","+","$","#","é"}
if pass == letters then
print("weak password")
elseif pass == letters and numbers then
print ("mid password")
elseif pass == letters and numbers and symbols then
print ("stong password!!")
end
When I run the code it works but it doesn't respond as weak password or mid password or strong password
Your comparisons are all completely wrong.
pass == letters
: This compares the read password string to the table letters
. Values of different types are never equal in Lua. Even if the array was "stringified" as in JS this would still not correctly capture the intention (you're not trying to check against the sorted alphabet)pass == letters and numbers
: This contains the same mistake plus a second one: numbers
is a table and thus always truthy. This is equivalent to pass == letters and true
which is just pass == letters
.pass == letters and numbers and symbols
again repeats the mistake and is thus equivalent to pass == letters
which is still always false
.Instead of comparing, you may use pattern matching to determine whether the password matches your criteria:
local pass = io.read()
if pass:match"[A-Za-z]*" then -- password consists only of letters; may be empty
print("weak password")
elseif not pass:match"[^A-Za-z0-9]" then -- password contains no characters except letters and numbers => password consists of letters and numbers
print("mid password")
elseif pass:match"[A-Za-z]" and pass:match"[0-9]" and (pass:match"[>!&+$#]" or pass:match"é") then
-- password contains at least one letter, one digit and a symbol; é is represented as two characters in UTF-8 and must thus be treated specially
print("strong password!!")
end -- else-branch is left as an exercise to the reader
You might want to use the character classes %a
and %d
here. Keep in mind that these may be locale specific, treating é
for instance as a letter rather than a symbol.