In Lua, a table is a highly flexible data structure that can represent arrays, dictionaries, and sets. By default, table assignment in Lua is by reference, meaning that if you directly assign a table to another variable, both variables reference the same table object. If you need to deep copy a table, you must manually traverse and copy its contents.
luafunction deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- Non-table types can be copied directly copy = orig end return copy end -- Usage example: local tbl = {1, 2, {3, 4}} local tbl_copy = deepcopy(tbl) print(tbl[3][1]) -- Output 3 tbl_copy[3][1] = 300 print(tbl[3][1]) -- Still outputs 3, indicating true copying
The deepcopy function recursively copies a table and its nested tables. It first checks the type of the original object; if it is a table, it creates a new table and recursively copies each key and value from the original table to the new one. For non-table types, such as numbers or strings, it copies them directly. Additionally, the function handles any existing metatables.
Recursive copying ensures the independence of all levels within the table, so modifying the copied table does not affect the original table. This is particularly useful when dealing with multi-level nested data structures.
Although effective, this method may consume more resources when dealing with very large or deeply nested tables. Therefore, in practical applications, you should consider whether to perform a deep copy based on specific circumstances, such as the size and complexity of the table.