测试在LUA中变量是否包含数字或字母或者两者都有/无

我正在尝试找出如何在lua中检查一个字符串变量中是否包含任何字母或数字,比如:

myAwesomeVar = "hi there crazicrafter1"

if myAwesomeVar(有字母和数字) then
    print("它有字母和数字!")
elseif myAwesomeVar(有字母但没有数字) then
    print("它有字母!但没有数字...")
elseif myAwesomeVar(没有字母和数字) then
    print("它没有字母或数字...")
elseif myAwesomeVar(没有字母,但有数字) then
    print("它没有字母,但它有数字!")
end

我知道这个参数有些不正确,但这是我代码输出的目标:

它有字母和数字!

点赞
用户2858170
用户2858170

正如 Egor 建议的那样,你可以写一个函数来检查一个字符串是否包含任何数字或字母...

Lua 使用字符串模式进行方便的字符串分析。

function containsDigit(str)

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

end

我敢打赌你也能为字母做同样的事情。参考 Lua 5.3 参考手册 6.4.1:字符串模式

然后你可以像这样做:

local myString = "hello123"
if containsDigit(myString) and containsDigit(myString) then
  print("contains both")
end
2017-12-03 20:13:20