Page 1 of 1

Move item from one table to another properly?

Posted: Thu Dec 29, 2011 6:35 am
by Jasoco
Is there a better way to move an entire table entry from one table to another than deleting the first and recreating it in the second?

By which I mean everything under the table entry. Every key value pair.

Code: Select all

table1 = {
  item1 = { stuff }
}

table2 = {
}
Move item1 from table1 to table2?

Re: Move item from one table to another properly?

Posted: Thu Dec 29, 2011 7:15 am
by ivan
Here's a neat trick which you might find useful:

Code: Select all

local a = { 1, 2, 3, 4, 5, 6, }

local b = { unpack(table1) }
It copies all of the values from table a into table b.
I don't think it would work if you want to copy over the table keys though.

Re: Move item from one table to another properly?

Posted: Thu Dec 29, 2011 8:34 am
by Robin
So you want the situation to go from

Code: Select all

    table1 = {
      item1 = { stuff }
    }

    table2 = {
    }
to

Code: Select all

    table1 = {
    }

    table2 = {
      item1 = { stuff }
    }
?

Then why not do

Code: Select all

table2.item1 = table1.item1
table1.item1 = nil

Re: Move item from one table to another properly?

Posted: Thu Dec 29, 2011 9:08 am
by Jasoco
Robin wrote:So you want the situation to go from

Code: Select all

    table1 = {
      item1 = { stuff }
    }

    table2 = {
    }
to

Code: Select all

    table1 = {
    }

    table2 = {
      item1 = { stuff }
    }
?

Then why not do

Code: Select all

table2.item1 = table1.item1
table1.item1 = nil
Will that transfer every aspect of the original item1 including all nested tables contained therein? What about any functions that might also be contained or images, canvases, whatever that may or may not also be included as part of the table?

Re: Move item from one table to another properly?

Posted: Thu Dec 29, 2011 9:35 am
by Robin
Yes.

In Lua, everything is basically references, so doing a = b will make a point to the same object as b.

Re: Move item from one table to another properly?

Posted: Fri Dec 30, 2011 3:29 pm
by Taehl
And if you do that, and change B, then A would be changed too! Took me a while to wrap my head around that when starting out in Lua. Can cause some subtle bugs if you ever assume it'll behave otherwise.

Re: Move item from one table to another properly?

Posted: Sun Jan 01, 2012 8:50 pm
by pauloborges
I dunno if this is what you want, but I think you can transfer all (key, value) pairs from one table to another doing this
(at least is scalable):

Code: Select all

table1 = {
	key = 'value', --string key
	[2] = 123, -- number key
	-- etc
}

table2 = {}

for key,value in pairs(table1) do
	table2[key] = value
end

table1 = {} -- or nil, depends of what you want
another great thing in Lua is the facility to swap variables:

Code: Select all

table1 = { ... }
table2 = { ... }

table1, table2 = table2, table1