help needed with variables (and pointers?) please

Hi

So I have a weird problem. I suspect it comes from my lack of experience with Lua - I’ve programmed with a number of other languages and haven’t seen this before.

I am creating a super simple particle system. I have one variable that has a series of properties defining the structure of the different particle systems. I then assign one of the elements to another variable so that I can manipulate it.

This works fine, however when I manipulate the new variable it edits the values of the original variable.

particle\_data[particleSystem].delay = 10particleProperties = {} particleProperties = particle\_data[particleSystem] particleProperties.delay = 20 -- particle\_data[particleSystem] now = 20

I can only assume that when I set the particleProperties variable it’s a pointer to the particle_data array and not a copy of it. Is there a way to change this so that the particleProperties variable is independent and doesn’t affect anything else?

Not sure how clearly I am explaining myself… hopefully someone understands :slight_smile:

Naturally since I’ve posted the question I now have something that works - but it’s not ideal so I’m open to other suggestions.

What I have ended up doing is creating a temp table to store the data so that get’s manipulated instead of the original table.

 local u = { } for k, v in pairs( particle\_data[particleSystem] ) do u[k] = v end

HI,

Your understanding is exactly right: in Lua, you only manipulate pointers to tables (http://www.lua.org/pil/2.5.html).  Your method of copying a table will work just fine for simple tables.  If your original table has sub-tables, though, those would need to be copied too.  You might find this helpful: http://lua-users.org/wiki/CopyTable.

  • Andrew

There is also a table.copy function mentioned here: http://docs.coronalabs.com/api/library/table/index.html

Thanks for the additional pointers. Very useful! :slight_smile:

Naturally since I’ve posted the question I now have something that works - but it’s not ideal so I’m open to other suggestions.

What I have ended up doing is creating a temp table to store the data so that get’s manipulated instead of the original table.

 local u = { } for k, v in pairs( particle\_data[particleSystem] ) do u[k] = v end

HI,

Your understanding is exactly right: in Lua, you only manipulate pointers to tables (http://www.lua.org/pil/2.5.html).  Your method of copying a table will work just fine for simple tables.  If your original table has sub-tables, though, those would need to be copied too.  You might find this helpful: http://lua-users.org/wiki/CopyTable.

  • Andrew

There is also a table.copy function mentioned here: http://docs.coronalabs.com/api/library/table/index.html

Thanks for the additional pointers. Very useful! :slight_smile: