如何在 Lua 中制作密码检查器

How to make a password checker in Lua

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

当我 运行 代码工作时,它不会响应弱密码或中等密码或强密码

你的比较都是完全错误的。

  • pass == letters:这会将读取的密码字符串与 table letters 进行比较。 Lua 中不同类型的值永远不相等。即使数组像 JS 中那样被“字符串化”,这仍然无法正确捕捉意图(你不是在尝试检查排序的字母表)
  • pass == letters and numbers:这包含同样的错误加上第二个错误:numbers 是一个 table,因此总是真实的。这相当于 pass == letters and true 只是 pass == letters.
  • pass == letters and numbers and symbols 再次重复错误,因此等同于 pass == letters 仍然总是 false.

您可以使用模式匹配来确定密码是否符合您的条件,而不是比较:

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

您可能想在此处使用字符 类 %a%d。请记住,这些可能是特定于区域设置的,例如将 é 视为字母而不是符号。