如何检查子字符串

a = "hello"
b = "hi"

io.write("enter a or b or both:")
c = io.read()

if c == "hello" then
    print(b)
elseif c == "hi" then
    print(a)
elseif c == "both" then
    print(a .. " " .. b)
else
    print("unknown word")
end

问题在于当我输入 hello hi 时,它会显示 unknown word

我该如何解决呢? 我也尝试使用表格,例如 d = {}, d.a = "hello", d.b = "hi",但是还是同样的问题。

点赞
用户1009479
用户1009479

== 用于测试相等性。但字符串 "hello hi" 既不等于 "hello" 也不等于 "hi"。要测试它是否包含子字符串,请使用模式匹配:

local found = false
if c:match("hello") then
    print(a)
    found = true
end
if c:match("hi") then
    print(b)
    found = true
end
if not found then
    print ("unknown word")
end
2014-05-15 13:22:30
用户107090
用户107090

如果你想比较单词而不是子字符串,可以尝试以下代码:

function normalize(x)
    return " "..x.." "
end

mywords=normalize("hello hi")

function ok(x)
    return mywords:match(normalize(x))~=nil

end

print(ok("hello"))
print(ok("hi"))
print(ok("high"))
2014-05-15 14:26:38