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
相关产品推荐
相关产品推荐

