lua-users home
lua-l archive

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


Thank you for your detailed explanation.

The assignment operator does almost the same thing both in Lua and
Python whereas Python provides deepcopy() to do the aforementioned
deep copy.

>As you can see, there's a lot of possible ways to do this, as well as
>potential issues, such as if there are recursive tables (tables that

^^^^^^^^^^^^^^^^^^^^^^^^^^^
>link to themselves).
  ^^^^^^^^^^^^^^^^^
Could you give me a example(i.e recursive tables). I could not find much
information about it on Google(keyword: Lua recursive tables).

tab = {};
tab ={tab};
I don't think `tab` is a  recursive table indeed.

Thank you for your attention to my question.

On Thu, Jan 21, 2021 at 5:51 PM Scott Morgan <blumf@blueyonder.co.uk> wrote:
>
> On 21/01/2021 03:25, 孙世龙 sunshilong wrote:
> > How to create a new table based on an already existed table (through
> > Lua or C API)?
>
> If you know C, it helps to think of table values like they are pointers.
> You don't copy the contents of a table, just the pointer to it.
>
> What you want is a table copy (or clone) function, but you have two
> choices on how to implement that; a shallow copy, or a deep copy.
>
> Shallow copy just copies the first level of values in the source table.
>
> Deep copy goes through any tables within the source table and copies
> them too.
>
> There is also a question about how to handle the the table's metatable
> data (and in a deep copy, any sub-table's metatable)
>
> As you can see, there's a lot of possible ways to do this, as well as
> potential issues, such as if there are recursive tables (tables that
> link to themselves). So the Lua team don't provide a copy operator or
> function as they can't know what people need.
>
> It is easy to write simple table copy functions that match your
> requirements:
> http://lua-users.org/wiki/CopyTable
>
> Scott