【问题标题】:Check if something has children in ROBLOX Lua?检查 ROBLOX Lua 中是否有子项?
【发布时间】:2016-11-09 02:52:45
【问题描述】:

我需要检查 ROBLOX Lua 中是否有子对象。我知道FindFirstChild(string) 会找到名称与string 匹配的第一个孩子,我一直在使用它来查看实例中是否有某个孩子,但现在我想看看它是否有任何孩子。我希望得到类似的东西:

if Instance:GetChildren() then
  --Do something
end

我该怎么做?

【问题讨论】:

    标签: lua roblox


    【解决方案1】:

    您可以通过以下方式找到答案:

    x = 0
    
    for i, v in pairs(script:GetChildren()) do
        x += 1
    end
    
    if x > 0 then
        print("it has children")
    end
    

    这不是最有效的,但它非常简单且有效

    【讨论】:

      【解决方案2】:
      if Object.GetChildren() then
         --code here
      end
      

      【讨论】:

      • 对于点表示法,您必须将接收器对象作为第一个参数传递,或者使用不带参数的:(冒号)表示法。所以应该是Instance:GetChildren()。另外,请在代码中添加一些描述或文档链接。
      【解决方案3】:

      我建议使用主题标签运算符或table.getn

      -- Hashtag
      if(table.getn(Instance:GetChildren()) > 0) then
          -- ...
      end
      
      if(#Instance:GetChildren() > 0) then
          -- ...
      end
      

      【讨论】:

        【解决方案4】:

        这个方法会得到一个Instance的children表,并检查它是否大于0,这意味着它有children。

        if #Instance:GetChildren() >0 then 
          --It has children!
        end
        

        【讨论】:

          猜你喜欢
          • 2020-05-12
          • 2021-10-01
          • 2021-08-23
          • 2021-10-12
          • 1970-01-01
          • 2021-12-28
          • 1970-01-01
          • 2013-01-14
          • 2017-03-26
          相关资源
          最近更新 更多