Skip to content

Commit b956329

Browse files
authored
New DeepClone code snippet
I've made a bit more documented of a code snippet to help scripters navigate their way through it, considering not everyone viewing would be experienced. This take on the deep clone snippet also gives a faster result, meaning the code is ran faster and you get your value returned faster. OLD: **0.0000051** NEW: **0.0000034** The difference may be small but definitely in some cases noticeable and useful. This is due to the usage of the generalized iterator. Also simplifying the code with ternary operators. But, I believe my take on this new snippet would definitely be faster, and also educate other scripters better, even spiking their curiosity in code simplification if not familiar with ternary operators. All in short, I believe It's a great take.
1 parent 1d1a378 commit b956329

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

content/en-us/luau/tables.md

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -291,14 +291,21 @@ local clone = table.clone(original)
291291
To copy a more complex table with nested tables inside it, you'll need to use a recursive function similar to the following:
292292

293293
```lua
294-
local function deepCopy(original)
294+
-- The function used for deep copying a table.
295+
local function deepCopy(original)
296+
-- Define the new table for the copy
295297
local copy = {}
296-
for k, v in pairs(original) do
297-
if type(v) == "table" then
298-
v = deepCopy(v)
299-
end
300-
copy[k] = v
298+
299+
-- Loop through the original table to clone
300+
for key, value in original do
301+
-- If the type of the value is a table,
302+
-- then deep copy it to the key (index).
303+
-- Else (or) the type isn't a table,
304+
-- assign the default value to the index instead.
305+
copy[key] = type(value) == "table" and MY_deepCopy(value) or value
301306
end
307+
308+
-- Return the finalized copy of the deep cloned table
302309
return copy
303310
end
304311
```

0 commit comments

Comments
 (0)