【发布时间】:2020-04-20 04:54:44
【问题描述】:
我正在尝试检查字符串中是否有某些单词。到目前为止,我创建了一个函数,如果该单词存在于字符串中,则该函数将存储在表中,然后如果该单词在字符串中,则该函数打印一条消息,否则打印其他消息。
这是 MWE:
stg = "In this string the words sky, dog, frog can be found"
function highlight(str)
local test = {str:find("sky"),str:find("car"),str:find("glass")}
local start, fim
for k, v in ipairs(test) do
if v ~= nil then
print("There's something")
elseif v == nil then
print("There's nothing")
end
end
end
highlight(stg)
奇怪的是:该函数只识别正在检查的第一个单词,即单词sky。如果stg 字符串没有匹配的单词,则函数不返回任何内容。甚至没有消息There's nothing。
如何使函数检查字符串中是否存在或缺少单词并正确打印消息?
【问题讨论】:
-
因为
test = {1,nil,nil},但nil相当于擦除元素,即就像从表格中删除一样。 -
好的,但是如果我有
stg = "In this string the words glass, dog, frog can be found",则该函数找不到玻璃。为什么?我不应该有test = {nil, nil, 1}吗?如果是这样,那么条件句就会指责有事。