【问题标题】:Function doesn't return message when value is missing缺少值时函数不返回消息
【发布时间】: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}吗?如果是这样,那么条件句就会指责有事。

标签: function lua lua-table


【解决方案1】:

ipairs 迭代器在找到 nil 值时停止,但 string.find 有时会返回 nil。这意味着在您的循环中,v 永远不会是 nil

一种解决方案是只将搜索字符串放入表中并在循环内调用string.find

stg = "In this string the words sky, dog, frog can be found"

function highlight(str)
    local test = {"sky","car","glass"}
    for k, v in ipairs(test) do
        if str:find(v) then
            print("There's something")
        else
            print("There's nothing")
        end
    end
end

highlight(stg)

【讨论】:

    【解决方案2】:

    使用table.pack 并按索引进行迭代。

    --[[
    -- For Lua 5.1 and LuaJIT
    function table.pack(...)
        return { n = select("#", ...), ... }
    end
    --]]
    
    stg = "In this string the words sky, dog, frog can be found"
    
    function highlight(str)
        local test = table.pack((str:find("sky")),(str:find("car")),(str:find("glass")))
        for n = 1, test.n do
            local v = test[n]
            if v ~= nil then
                print("There's something")
            else
                print("There's nothing")
            end
        end
    end
    
    highlight(stg)
    

    Live example on Wandbox

    【讨论】:

    • 如果 string.find 得到匹配,它将返回 2 个值。这可能会导致test.n 比应有的多 1。也许在最后一次调用周围加上括号以将其截断为一个值。
    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2018-07-22
    相关资源
    最近更新 更多