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

Lua脚本问题:检测TextBox.Text是否包含数组字符串失败

解决TextButton检测TextBox文本是否包含数组字符串的问题

嘿,我来帮你搞定这个脚本问题!你的代码没法正常运行,核心问题是**string.match()根本不支持直接传入数组作为匹配参数**——它需要的是单个字符串模式。下面给你两种实用的修复方案,挑你觉得顺手的用就行:

方案1:遍历数组逐个检查(直观易理解)

这种方法逻辑很直白,就是循环数组里的每个关键词,挨个检查输入文本里有没有它。好处是即使关键词里有特殊字符也不会出问题,适合新手:

-- 获取控件引用
local textBox = script.Parent.Parent:WaitForChild('TextBox')
local resultLabel = script.Parent.Parent:WaitForChild('TextLabel')
-- 要检测的关键词数组
local targetWords = {'test1','test2','test3'}

-- 绑定按钮点击事件(注意用大写C的Connect,小写connect已经被弃用啦)
script.Parent.MouseButton1Click:Connect(function()
    local isFound = false
    local matchedWord = ""
    
    -- 遍历每个关键词
    for _, word in ipairs(targetWords) do
        -- string.find第四个参数设为true,把word当作纯文本匹配,避免特殊字符干扰
        if string.find(textBox.Text, word, 1, true) then
            isFound = true
            matchedWord = word
            break -- 找到一个就停止循环,省点性能
        end
    end

    -- 更新提示文本
    if isFound then
        resultLabel.Text = string.format("The word %s was found in the table.", matchedWord)
    else
        resultLabel.Text = string.format("The word %s was not found in the table.", textBox.Text)
    end
end)

方案2:构建正则模式批量匹配(更高效)

如果你的关键词里没有正则特殊字符(比如%、*、+这类),可以把数组转成用|分隔的正则模式串,一次性完成所有匹配,代码更简洁:

local textBox = script.Parent.Parent:WaitForChild('TextBox')
local resultLabel = script.Parent.Parent:WaitForChild('TextLabel')
local targetWords = {'test1','test2','test3'}

-- 把数组拼接成正则模式:"test1|test2|test3"
local matchPattern = table.concat(targetWords, "|")

script.Parent.MouseButton1Click:Connect(function()
    -- 一次性匹配所有关键词
    local matchedWord = string.match(textBox.Text, matchPattern)
    
    if matchedWord then
        resultLabel.Text = string.format("The word %s was found in the table.", matchedWord)
    else
        resultLabel.Text = string.format("The word %s was not found in the table.", textBox.Text)
    end
end)

额外提示

  • 如果需要不区分大小写的匹配,可以把文本和关键词都转成小写后再比较,比如string.lower(textBox.Text)和string.lower(word)。
  • 如果关键词里有正则特殊字符(比如test%),方案2需要先给特殊字符转义,比如用string.gsub(word, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")处理每个关键词后再拼接模式串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:20:39