【问题标题】:Removing entry from table从表中删除条目
【发布时间】:2013-06-27 10:29:59
【问题描述】:

无法从表中删除条目。

这是我的代码

dropItem = dropList[ math.random( #dropList ) ]
dropSomething[brick.index] = crackSheet:grabSprite(dropItem, true)
dropSomething[brick.index].x = brick.x
dropSomething[brick.index].y = brick.y
dropSomething[brick.index].name = dropItem
dropSomething[brick.index].type = "dropppedItems"

碰撞

function bounce(event)
        local item = event.other
        if item.type == "dropppedItems" then
            if item.name == "bomb" then
                Lives = Lives - 1
                LivesNum.text = tostring(Lives)
            end
        item:removeSelf();
        end     

end

我尝试过的:

item:removeSelf(); -- removes the whole table
item = nil -- seems to do nothing, the object continue 
           -- to move and i still see the image

我可以从屏幕上删除对象的唯一方法是使用
transition.to(item, {time = 100, alpha = 0})

隐藏它

【问题讨论】:

  • event.other = nil 呢?
  • 我只能假设您的函数必须位于事件侦听器的顶部,否则您可以为其添加其他代码

标签: arrays sdk lua coronasdk lua-table


【解决方案1】:

那里的项目对象应该是您的实际项目的副本。意思是,它不像一个指针。所以如果你想从表格中移除一个项目,你应该在表格中到达它。

你可以像这样修改你的代码:

dropItem = dropList[ math.random( #dropList ) ]
dropSomething[brick.index] = crackSheet:grabSprite(dropItem, true)
dropSomething[brick.index].x = brick.x
dropSomething[brick.index].y = brick.y
dropSomething[brick.index].name = dropItem
dropSomething[brick.index].type = "dropppedItems"
dropSomething[brick.index].id = brick.index

function bounce(event)
        local item = event.other
        if item.type == "dropppedItems" then
            if item.name == "bomb" then
                Lives = Lives - 1
                LivesNum.text = tostring(Lives)
            end
        dropSomething[item.id]:removeSelf();
        dropSomething[item.id] = nil
        end     
end

假设反​​弹函数可以到达 dropSomething 表

【讨论】:

    【解决方案2】:

    如果你想要从表中移除对象,你可以使用函数'table.remove()',非常好用。

    要做到这一点,您有两种方法: 一种是使用自定义函数,另一种是不使用。

    我建议使用自定义函数。

    为此,您可以执行类似的操作

        removeFromTable = function(tbl, lookfor)
           for i,v in pairs(tbl)do
              if(v.Name==lookfor)then -- change that to whatever you will use as a identification
                 table.remove(tbl, i);
              end;
           end;
        end;
    

    假设您在 RBLX_Lua 中,这将起作用。我不确定它是否适用于其他 lua“版本”。它需要您为表中的每个对象都有一个识别“标签”,您可能已经考虑到它看起来像是在用物品制作游戏。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2011-12-20
      • 1970-01-01
      • 2013-04-24
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多