How do I empty a table when using reference?

Find quick help here to get you started with Hollywood
Post Reply
Bugala
Posts: 1168
Joined: Sun Feb 14, 2010 7:11 pm

How do I empty a table when using reference?

Post by Bugala »

When I make reference to a table, everything I do to the reference, will also happen to the original table.

Code: Select all

mytable = {}
mytable[1] = {}
mytable[1].test = "yep"


reftable = mytable[1]

DebugPrint(reftable.test)

reftable.another = "another"
DebugPrint(mytable[1].another)

reftable = {}

DebugPrint(mytable[1].test)
DebugPrint(reftable.test)
However, when I try to empty that table using

Code: Select all

reftable = {}
instead of cleaning both tables as was my intention, the original stays, since I guess when using reftable = {} it doesn't empty the table, but empties the reference.


So how can I empty the original table using reference, or do I have to manually empty every item from it?


Point is that this table is holding several number in it: table = {1, 2, 3, 4, 5}, and as I am assigning new numbers to it, of what there might be different amount than there is currently, I was wanting to first empty that table before assigning the new numbers inside to avoid one of the old numbers staying there.

As example:

oldtable = {1, 2, 3, 4, 5, 6}

Newtable = {10, 20, 30, 40}

except now when I replace the old one with new one, I end up with:

NewTable = {10,20, 30, 40, 5, 6}
User avatar
airsoftsoftwair
Posts: 5425
Joined: Fri Feb 12, 2010 2:33 pm
Location: Germany
Contact:

Re: How do I empty a table when using reference?

Post by airsoftsoftwair »

By doing

Code: Select all

reftable = {}
you don't empty the table but you're creating a new one. Obviously, this doesn't have any effect on any prior references. You need to kill those references individually since table references are completely unaware of other references that might exist.
Bugala
Posts: 1168
Joined: Sun Feb 14, 2010 7:11 pm

Re: How do I empty a table when using reference?

Post by Bugala »

A feature request, something like:

Code: Select all

EmptyTable(table)
This way I could do for example:

Code: Select all

TableUnderWork = MyTable[1][2]

EmptyTable(TableUnderWork)
TableUnderWork[3] = "test"

DebugPrint(MyTable[1][2][3])
This would help in a situation where you need to make the table empty, but you are accessing it through reference.
SamuraiCrow
Posts: 475
Joined: Fri May 15, 2015 5:15 pm
Location: Waterville, Minnesota USA

Re: How do I empty a table when using reference?

Post by SamuraiCrow »

Try this:

Code: Select all

Function p_ClearTable(t)
	For k,v In Pairs(t)
		t[k]=Nil
	Next
	Return(t)
EndFunction

Global tab={1,2,3,4,5,{"a","b"}}
tab=p_ClearTable(tab)
DebugPrint(TableItems(tab))
I'm on registered MorphOS using FlowStudio.
Bugala
Posts: 1168
Joined: Sun Feb 14, 2010 7:11 pm

Re: How do I empty a table when using reference?

Post by Bugala »

Thanks, that is actually a better idea than the one I had.
Post Reply