A Question about Table ! ^^

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Neolitik
Citizen
Posts: 55
Joined: Sun Jun 28, 2009 3:13 pm

A Question about Table ! ^^

Post 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)
User avatar
kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Location: Madrid, Spain
Contact:

Re: A Question about Table ! ^^

Post 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).
When I write def I mean function.
Neolitik
Citizen
Posts: 55
Joined: Sun Jun 28, 2009 3:13 pm

Re: A Question about Table ! ^^

Post by Neolitik »

Thank for your reply ,
The first example is very useful for me ! A sort of table pointer !!

By !
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: A Question about Table ! ^^

Post by Robin »

Neolitik wrote:A sort of table pointer !!
Sort of, indeed. In Lua, everything is a reference.
Help us help you: attach a .love.
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 205 guests