【问题标题】:0 Checking if TextBox.Text contains the string in the table. But it doesn't work? Lua0 检查 TextBox.Text 是否包含表中的字符串。但它不起作用?卢阿
【发布时间】:2018-04-25 20:32:53
【问题描述】:

我正在 TextButton 脚本中创建一个脚本,该脚本将检查 TextBox 是否包含表格中的任何单词或字符串。

text = script.Parent.Parent:WaitForChild('TextBox')
label = script.Parent.Parent:WaitForChild('TextLabel')

a = {'test1','test2','test3'}

script.Parent.MouseButton1Click:connect(function()
     if  string.match(text.Text, a) then
     label.Text = "The word "..text.Text.." was found in the table."
 else
     label.Text = "The word "..text.Text.." was not found in the table."
 end
 end)

但它给出了一个错误 string expected, got table. from line 7 这是指行 if 字符串。匹配....

有没有办法获取表格中的所有文本?

正确的做法是什么?

【问题讨论】:

    标签: lua roblox


    【解决方案1】:

    哦,男孩,关于这个有很多话要说。

    错误信息

    是的。

    不,说真的,答案是肯定的。错误信息完全正确。 a 是一个表值;您可以在第三行代码中清楚地看到这一点。 string.match 需要一个字符串作为它的第二个参数,所以它显然会崩溃。

    简单的解决方案

    使用for 循环并分别检查a 中的每个字符串。

    found = false
    for index, entry in ipairs(a) do
      if entry == text.Text then
        found = true
      end
    end
    if found then
    ... -- the rest of your code
    

    更好的*解决方案

    在 Lua 中,如果我们想知道单个元素是否在集合中,我们通常会利用表实现为哈希图这一事实,这意味着它们在查找键时非常快。

    为此,首先需要更改表格的外观:

    a = {["test1"] = true, ["test2"] = true, ["test3"] = true}
    

    然后我们可以只用一个字符串索引a,看看它是否包含在整个集合中。

    if a[text.Text] then ...
    

    * 实际上,只要您的表格中只有 几个 元素,这与第一个解决方案一样好。只有当您有几百个条目您的代码需要尽可能快地运行时,它才会变得相关。

    【讨论】:

      猜你喜欢
      • 2014-03-02
      • 2020-02-26
      • 2013-10-26
      • 2022-01-17
      • 2013-11-28
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多