lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


----- Original Message ----- 
> From: "Tom Spilman" <tom@sickheadgames.com>
> > From: "Tobias Käs" <tobias.kaes@gmx.de>
> >
> > The reason is, there are many ways to copy a table, and you cannot
define
> > a simple "standard" way.
>
> I believe copying the tables are the simple part.  The questions is what
> is done with non-table keys and values.
>

I don't agree, tables cannot be handled easily either, at least not in a
"standard" way.
The "easy" part are the objects like numbers and strings.
(Better don't consider coroutines, or userdata which represents a network
connection... thats getting too complex. There might be other objects which
cannot be copied at all, and a reference copy might not be desired either.)

> > An example is: How is table recursion handled? The way you want to deal
> > with this is application dependant.
>
> Wouldn't general consensus be to recursively make copies of nested
> tables or just take a reference to them?
>
There is no "general" solution, as your "or" shows, there are (at least)
two.

A recursive table is a table like this:

a = {}
a.ref = a

Those tables can appear in many different forms, and at least I use them
quite often, for example in double linked userdata and tables. (metatable of
userdata refers to table; table to userdata)

In the function you have given, recursion would lead to an infinite loop. I
can think of at least three ways to handle this:
- don't copy recursive tables (thats what I will do since it is the simplest
way ;-)
- keep the reference to the original recursive table (which breaks the
recursion, but still simple)
- make a copy which is recursive in the new table (could be complex)

Moreover, you cannot predict if in case of nested tables you want to make a
reference or deep copy of the table. Often it will _not_ be enough to make a
general decision for the whole copy process.

Of course you could add a metatable function to every table and userdata,
which decides how to copy it, but that might lead to a lot of unnecessary
work (which you wanted to avoid ;-) and blow up lua scripts.

And here another example: how to copy metatables? Again there is no
"general" solution - reuse them or make a deep copy? I do use them to store
additional information, in case of userdata objects. Should I now make a
"metatable of a metatable" to define how to copy it? ;-)

I am still of the opinion that it is the best (and fastest) solution to make
a function of your own, since you know which features you need. I doubt you
can insert any hard to find bugs, since its easy to test with "simple"
tables.