You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua中for循环变量取索引输出nil,如何存储首个匹配字符串结果

错误原因

  • word 是循环遍历过程中取出的单个字符串变量,并非存储所有匹配结果的数组,Lua 中字符串不支持 [索引] 方式取值,因此 word[1] 会返回 nil。
  • 原函数没有返回值,无法直接将匹配结果赋值给外部变量。

解决方案

如果只需要获取首个匹配结果,找到匹配项后直接终止循环并返回即可,修改后代码如下:

local words = { 
    "One - Test", 
    "Two - Test", 
    "Three - Test"
}

local find = "Test"

local function getFirstMatchWord(partialName)
    partialName = partialName:lower()
    for _, word in ipairs(words) do
        if string.find(word:lower(), partialName) then
            -- 找到第一个匹配项直接返回,不再执行后续循环
            return word
        end
    end
    -- 无匹配项时返回nil
    return nil
end

-- 调用函数将结果存储到变量
local targetWord = getFirstMatchWord(find)
print(targetWord) -- 输出:One - Test

如果后续需要获取所有匹配结果,可以将匹配项存入数组后返回,示例如下:

local function getAllMatchWords(partialName)
    partialName = partialName:lower()
    local matchList = {}
    for _, word in ipairs(words) do
        if string.find(word:lower(), partialName) then
            table.insert(matchList, word)
        end
    end
    return matchList
end

local allMatches = getAllMatchWords(find)
print(allMatches[1]) -- 输出首个匹配结果:One - Test
print(#allMatches) -- 输出匹配总数:3

内容的提问来源于stack exchange,提问作者user15915698

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 02:15:03