Page 1 of 1

A Question about Table ! ^^

Posted: Sun Apr 11, 2010 8:22 pm
by Neolitik
Hello all !

I try to transfert a table into a table ...( Copy , paste , delete )
This code is Ok , but i don't know if is the best method for that ??? :?

Code: Select all

Cam={}
Cam.Obj={}

function Cam:Add(t)
table.insert(Cam.Obj,t)
t=nil
return t
end

Bla={x=100;y=100;z=100}
Bla=Cam:Add(Bla)

Re: A Question about Table ! ^^

Posted: Sun Apr 11, 2010 9:10 pm
by kikito
I don't understand what you want.

There are several ways of transfering a table to another table. It depends on how you define "transfering".

This inserts a member in Cam, called Obj, that points to the contents of the table Bla. But it is the same object; it is not "copied".

Code: Select all

Cam = {}
Bla={x=100, y=100, z=100}
Cam.Obj = Bla
print(Cam.Obj.x) -- prints '100'
Bla.x = 200
print(Cam.Obj.x) -- prints '200'
This makes a copy of Bla, instead of storing a reference to it. So changing Bla doesn't change Cam.Obj:

Code: Select all

Cam = {}
Bla={x=100, y=100, z=100}
Cam.Obj = {}
for k,v in pairs(Bla) do Cam.Obj[k] = v end
print(Cam.Obj.x) -- prints '100'
Bla.x = 200
print(Cam.Obj.x) -- prints '100'
Keep into account that this will work only if Bla is "flat" (contains integers, numbers, strings, etc, but not other tables). If Bla contains other tables, and you want to make a copy of them and not a reference, you will need a more complex function (probably recursive).

Re: A Question about Table ! ^^

Posted: Mon Apr 12, 2010 6:42 pm
by Neolitik
Thank for your reply ,
The first example is very useful for me ! A sort of table pointer !!

By !

Re: A Question about Table ! ^^

Posted: Mon Apr 12, 2010 8:20 pm
by Robin
Neolitik wrote:A sort of table pointer !!
Sort of, indeed. In Lua, everything is a reference.