lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



luaL_deepcopy( 'table' ) /* with refs */

Yes, please.

Why a C-version? It's just as easy [or: easier?] to do in Lua.

Here's a version I just quickly cobbled together (from something larger):

--- [ start of deepcopy.lua ] ---

if not std then std = {} end
local pub = std
local prv = {}

-- a structure copy primitive (able to deal with table values occuring more than once)
function prv.copy_table(src, dst, copies)
	local copy = %prv.copy_table

	for k, v in src do
		if type(v) == "table" then
			-- did we copy this one earlier?
			local nv = copies[v]

			if not nv then
				nv = {}
				copies[v] = nv
				copy(v, nv, copies)
			end

			dst[k] = nv
		else
			dst[k] = v
		end
	end

	return dst
end

-- a simple table-deep-copy-with-references helper thingy
function pub.deepcopy(tab)
	if type(tab) ~= 'table' then return end
	local ntab = {} -- the table-copy-to-be
	local tmap = { [tab] = ntab } -- the mapping to keep track of copied tables
	return %prv.copy_table(tab, ntab, tmap)
end

--- [ end of deepcopy.lua ] ---

Since I quickly stripped it down (and added some comments), I guess it's only semi-tested. So best check to see if all's well.

And, yes, it's Lua 4 code. But adapting it to Lua 5 looks like a matter of adding a pairs-call to the for-loop and removing two percentage signs [for them ol' upvalues... ;-)].

Note that this version only handles deep *value* copies [i.e. doesn't bother about keys (I never had any need for this ;-))]. If anyone needs more, they can take it from here.

Use and/or abuse at your convenience.

Ashwin.
--
no signature is a signature.