Reputation: 11
new to programming in Lua. Suppose I have a variable that contains a table element. For instance, Let objects be an array of something and I also have a variable 'a'.
a = objects[2] is what I do for some functionality in my program. If I then table.remove the 2nd element in the objects table, does 'a' get set to nil automatically?
Upvotes: 1
Views: 43
Reputation: 28950
Why don't you try it out?
local objects = {{}, {}}
local a = objects[2]
table.remove(objects, 2)
print("objects[2]", objects[2])
print("a", a)
Prints:
objects[2] nil
a table: 0x11196d0 (this value will be different for you)
You see a
is not nil
!
local objects = {{}, {}}
is equivalent to
do
-- this line creates a table and a local reference to that table named objects
local objects = {}
-- this line creates a table and stores a reference to it as objects[1]
objects[1] = {}
-- this line creates a table and stores a reference to it as objects[2]
objects[2] = {}
end
Now we create a
, a second reference to the table, objects[2]
refers to.
-- this creates a local reference to the table that objects[2] refers to as a
local a = objects[2]
And now we remove objects[2]
.
-- this line removes field 2 from the table, hence one of the referenes
table.remove(objects, 2)
Which in this case is equivalent to objects[2] = nil
That just removed one of the two existing references to that table. You assigned nil
to objects[2]
. So objects[2]
no longer refers to that table.
a
is still a reference to that table. Only if you set a
nil there will be no more references to that table and the table may be garbage collected as it is no longer accessible. You cannot delete tables in Lua. You can only assign nil to all its references and let the garbage collector do its thing.
Upvotes: 1