前言:
lua中table类型是一种数据结构用来帮助我们创建不同的数据类型,使用table在编程中是再常见不过的了,但是相应的也会碰到引用问题。
目标:
通过对以往的问题进行整理并结合别人的案例来提高自身的代码水平。
问题:
lua中table类型是引用传递,因此不能简单的通过“=”来复制来获得新表,否则改动其中一张表都会导致另一张表也被联动修改。解决办法是通过clone函数复制table:
function clone(object)--clone函数 local lookup_table = {}--新建table用于记录 local function _copy(object)--_copy(object)函数用于实现复制 if type(object) ~= "table" then return object ---如果内容不是table 直接返回object(例如如果是数字\字符串直接返回该数字\该字符串) elseif lookup_table[object] then return lookup_table[object]--这里是用于递归滴时候的,如果这个table已经复制过了,就直接返回 end local new_table = {} lookup_table[object] = new_table--新建new_table记录需要复制的二级子表,并放到lookup_table[object]中. for key, value in pairs(object) do new_table[_copy(key)] = _copy(value)--遍历object和递归_copy(value)把每一个表中的数据都复制出来 end return setmetatable(new_table, getmetatable(object))--每一次完成遍历后,就对指定table设置metatable键值 end return _copy(object)--返回clone出来的object表指针/地址 end
实例范例:
local a = { [{100, 200}] = { 300, 400}, 200, { 300, 500}, abc = "abc"} local myPolygon = { color="blue", thickness=2, npoints=4, {x=0, y=0}, {x=-10, y=0}, {x=-5, y=4}, {x=0, y=4} } local newtable = clone(a) local newtable2 = clone(myPolygon)
输出内容:
1 200 1 300 2 500 2 table: 0x7ffa43d06930 1 100 2 200 1 300 2 400 table: 0x7ffa43d06610 table: 0x7ffa43d068f0 abc abc ---以上是复制表a时的输出内容 后面以下是表myPolygon的输出内容 x 0 y 0 1 table: 0x7ffa43d064f0 x -10 y 0 2 table: 0x7ffa43d06a60 x -5 y 4 3 table: 0x7ffa43d06af0 x 0 y 4 4 table: 0x7ffa43d06b80 npoints 4 thickness 2 color blue