Lua Shallow vs Deep Copy: Cycles, Shared References and Metatables
Assigning a table does not copy it:
Both variables refer to the same object.
Shallow copy
Top-level fields are copied, but nested tables remain shared. Whether the metatable should be copied, shared, or omitted is a design choice—not a universal rule.
Deep copy with cycle preservation
| |
The memo table prevents infinite recursion and preserves shared references. This implementation deeply copies table keys but shares the original metatable. Depending on the data model, either decision may be wrong.
Functions, userdata, threads, and native resources cannot generally be cloned. Weak tables, protected metatables, object identity, and external handles also require explicit policies. In many applications, a type-specific clone method is safer than a generic deep-copy utility because it documents exactly which state is owned and which is shared.