--- Deep copies a table into a new table. -- Tables used as keys are also deep copied, as are metatables -- @param orig The table to copy -- @return Returns a copy of the input table localfunctiondeep_copy(orig) local copy iftype(orig) == "table"then copy = {} for orig_key, orig_value innext, orig, nildo copy[deep_copy(orig_key)] = deep_copy(orig_value) end setmetatable(copy, deep_copy(getmetatable(orig))) else copy = orig end return copy end
--- Copies a table into a new table. -- neither sub tables nor metatables will be copied. -- @param orig The table to copy -- @return Returns a copy of the input table localfunctionshallow_copy(orig) local copy iftype(orig) == "table"then copy = {} for orig_key, orig_value inpairs(orig) do copy[orig_key] = orig_value end else-- number, string, boolean, etc copy = orig end return copy end
例子如下: 深拷贝
1 2 3 4 5 6 7
local a = { aa = 1, bb = 2, cc = { dd = { ee = 3 } } } --local b = deep_copy(a) local b = shallow_copy(a) b.cc.dd.ee = 111 b.bb = 111 ngx.say(cjson.encode(a)) ngx.say(cjson.encode(b))