From b956329bc609507aee9d898863853b8b58ed8fa0 Mon Sep 17 00:00:00 2001 From: EnumEnv Date: Sat, 28 Sep 2024 22:08:36 +0200 Subject: [PATCH] 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. --- content/en-us/luau/tables.md | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/content/en-us/luau/tables.md b/content/en-us/luau/tables.md index 79d4c4a99..44b09952c 100644 --- a/content/en-us/luau/tables.md +++ b/content/en-us/luau/tables.md @@ -291,14 +291,21 @@ local clone = table.clone(original) To copy a more complex table with nested tables inside it, you'll need to use a recursive function similar to the following: ```lua -local function deepCopy(original) +-- The function used for deep copying a table. +local function deepCopy(original) + -- Define the new table for the copy local copy = {} - for k, v in pairs(original) do - if type(v) == "table" then - v = deepCopy(v) - end - copy[k] = v + + -- Loop through the original table to clone + for key, value in original do + -- If the type of the value is a table, + -- then deep copy it to the key (index). + -- Else (or) the type isn't a table, + -- assign the default value to the index instead. + copy[key] = type(value) == "table" and MY_deepCopy(value) or value end + + -- Return the finalized copy of the deep cloned table return copy end ```