Assigning a table does not copy it:
1 | local original = { score = 10 } |
Both variables refer to the same object.
Shallow copy
1 | local function shallowCopy(source) |
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
1 | local function deepCopy(value, copies) |
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.