How to clone a table fully?

table.clone() isnt actually clone a table fully. For example, if you have tables inside the cloned table, if you change something inside these tables it will replicate on the original table.

Code example:

local Def = {
    Table = {
        Boolean = false;
    };
}

local New = table.clone(Def)

New.Table.Boolean = true

print(Def.Table.Boolean) --it will print true

Is there any way to copy it and that it wont replicate to the original table?

4 Likes

I mean, couldn’t you just…

local Def = {
    Table = {
        Boolean = false;
    };
}

local New = Def   -- just define a variable as the initial table.

New.Table.Boolean = true

print(Def.Table.Boolean) --it will print true

i tried, but it still prints true

table.clone creates a shallow copy of the table (it doesn’t copy any sub-tables)

If you want to deep clone a table see https://create.roblox.com/docs/luau/tables#deep-clones

11 Likes

image

local function deepCopy(original)
	local copy = {}
	for k, v in pairs(original) do
		if type(v) == "table" then
			v = deepCopy(v)
		end
		copy[k] = v
	end
	return copy
end

local test = {
	lol = true,
	moretable = {lol1 = false}
}


local new = deepCopy(test)

new.moretable.lol1 = true
print(new)
print(test)

he solve it.

3 Likes

oh, didn’t knew about it, thank you.

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