lua-users home
lua-l archive

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


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