From e4e39449d879613c9251dcb5b56abdc5a27f7f9f Mon Sep 17 00:00:00 2001 From: Paul Liverman III Date: Sat, 16 Apr 2016 22:12:40 -0700 Subject: [PATCH] improved addChild, added removeChild --- src/pop/elements/element.moon | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/pop/elements/element.moon b/src/pop/elements/element.moon index be36652..536386a 100644 --- a/src/pop/elements/element.moon +++ b/src/pop/elements/element.moon @@ -1,5 +1,7 @@ import graphics from love import floor from math +import insert, remove from table +tonumber = tonumber class element new: (parent) => @@ -38,11 +40,28 @@ class element return @ addChild: (child) => - @child[#@child+1] = child + -- make sure we don't duplicate references + if child.parent + child.parent\removeChild(child) + + insert @child, child child.parent = @ return @ + -- remove child by index and return it OR remove child by reference + removeChild: (child) => + if tonumber(child) == child + -- remove indexed child, return it + @child[child].parent = false + return remove @child, child + else + for k,v in ipairs @child + if v == child + remove @child, k + return @ + error "Element \"#{child}\" is not a child of element \"#{@}\". Cannot remove it." + getChildren: => return @child