asd32
asd32

Reputation: 45

How to check for substrings

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~=a or b then    
    print ("unknown word")    
end

The problem is when I write both : hello hi, it is showing :unknown word.

How can I fix this? I also tried with table something like d={},d.a="hello",d.b="hi" but the same problem.

Upvotes: 1

Views: 72

Answers (2)

lhf
lhf

Reputation: 72312

If you want to compare words instead of substrings, try this:

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"))

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

== is used to test equality. But the string "hello hi" is neither equal to "hello" nor "hi". To test if it contains a substring, use pattern matching:

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

Upvotes: 3

Related Questions