What is the difference between the following Functions?

here is the Function Number #1:

function Utility:DeepTableReplica(Table)
local TableCopy = {};

	for Index,Value in Table do
		local IndexType, ValueType = type(Index), type(Value);
		TableCopy[Index] = Value;
	return TableCopy;

and the Function Number #2

function Utility.GetDeepCopy(Table)
	local Copy = {}

	for Index, Value in pairs(Table) do
		local IndexType, ValueType = type(Index), type(Value)

		if IndexType == "table" and ValueType == "table" then
			Index, Value = Utility.GetDeepCopy(Index), Utility.GetDeepCopy(Value)
		elseif ValueType == "table" then
			Value = Utility.GetDeepCopy(Value)
		elseif IndexType == "table" then
			Index = Utility.GetDeepCopy(Index)

		Copy[Index] = Value

	return Copy

am curious to know what are the difference between both the function , such as advantages,disadvantages…ect

1 Like

The first method returns a new table object, possibly referring to reference types within the table that was passed to it as a parameter. (those values are not created in the new table, they are only referenced.)

The second method performs a deep copy (a genuine clone) of the specified table parameter. What this means is that an entirely new table object will be created and returned. It will not refer to anything from the specified table parameter.

Say you have this table object:

local myTable = {
aReferenceType = {1, 2, 3};

local myOtherTable = myTable --//Note myOtherTable now references myTable. A deep copy is never performed

myOtherTable.aReferenceType[1] = 4

print(myOtherTable.aReferenceType[1]) --> prints 4
print(myTable.aReferenceType[1]) --> also prints 4, because they both refer to the same table object

In this example, obviously this is undesirable. So you can use a technique known as a deep copy to completely clone the table into a new one. Therefor, any changes you make to the new table will be completely independent from the old one. It won’t refer to anything from the old table.

I probably overcomplicated this a bit, but I hope it helps! :slight_smile:


i was curious about what the difference between the two functions due to the fact that they returned the same output/result but after your clarification, i understand now the difference, appreciate that

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.