How do you "clone" a table into a variable instead of referencing it?

Hi there,

consider this scenario

local tbl = {}
local varTbl = tbl-- This does not create a copy of 'tbl' but rather a reference

-- This does not happen with other data types Example: 
local str = "Hello"
local varStr = str -- This does not reference but rather make varStr equal to "Hello"

The variable ‘varTbl’ acts as a reference to ‘tbl’ and any changes done to it will replicate to the original table.

How do I get a table and store it in a variable without referencing it?



    local function shallowCopy(original)
    	local copy = {}
    	for key, value in pairs(original) do
    		copy[key] = value
    	end
    	return copy
    end
7 Likes

Oh damn, didn’t see that article. Dang I would’ve known how to do that but I thought there was something simpler than that.

Anyways, Thanks a bunch :slight_smile:

1 Like

I agree that it’s not very intuitive. It seems like cloning a table should be something in Lua, but it isn’t.

EDIT (09/19/2023):
table.clone() is now provided. For deep-copies, though, a custom function will still be needed.

3 Likes

just add table.copy or table.deepcopy

2 Likes