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

如何在Lua中使用string.find从字典表中查找包含指定字符串的条目

问题答案

直接使用string.find(songs, toFind)无法实现需求,string库的所有操作方法仅接受字符串类型作为操作目标,直接传入table类型参数会直接抛出类型不匹配错误。

你需要先遍历songs表的每一个子项,再对子项的name字段执行字符串匹配操作,示例实现代码如下:

local toFind = "Layla"

local songs = {
    {name = "Eric Clapton - Layla", id = "123"},
    {name = "Eric Clapton - I Shot The Sheriff", id = "321"}
}

-- 存储所有匹配的条目
local matchedSongs = {}
for _, song in ipairs(songs) do
    -- string.find第4个参数设为true表示使用纯文本匹配,避免toFind含特殊字符时出现意料外的匹配结果
    if string.find(song.name, toFind, 1, true) then
        table.insert(matchedSongs, song)
    end
end

如果只需要获取第一个匹配到的条目,不需要收集所有结果,可以在匹配成功后直接break终止循环即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:09:05