lua 引用导致问题解决方案

前言: 
lua中table类型是一种数据结构用来帮助我们创建不同的数据类型,使用table在编程中是再常见不过的了,但是相应的也会碰到引用问题。

目标: 
通过对以往的问题进行整理并结合别人的案例来提高自身的代码水平。

问题一: 
lua中table类型是引用传递,因此不能简单的通过“=”来复制来获得新表,否则改动其中一张表都会导致另一张表也被联动修改。解决办法是通过clone函数复制table:

function clone(object)
    local lookup_table = {}
    local function _copy(object)
        if type(object) ~= "table" then
            return object
        elseif lookup_table[object] then
            return lookup_table[object]
        end
        local new_table = {}
        lookup_table[object] = new_table
        for key, value in pairs(object) do
            new_table[_copy(key)] = _copy(value)
        end
        return setmetatable(new_table, getmetatable(object))
    end
    return _copy(object)
end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

问题二: 
当遇到table中key不是从1开始连续的,使用ipairs方式遍历会因找不到主键导致报错,解决办法换用pairs遍历,该方式不是通过table中的排列顺序遍历,而是通过hash值排列顺序来遍历。

问题三: 
循环表删除操作获得的结果不正确,这个问题很隐蔽通常不容易发现。导致这个问题的原因是删除表会导致表的结构被破坏,解决办法有: 
方法一、逆序删除

for i=#test,1,-1 do 
    if remove[test[i]] then
        table.remove(test,i)
    end
end
  • 1
  • 2
  • 3
  • 4
  • 5

方法二、while删除

local i=1
while i<=#test do
    if remove[test[i]] then
        table.remove(test,i)
    else 
        i=i+1
    end
end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

方法三、quick中提供的removeItem

function table.removeItem(list,item,removeAll)
    local rmCount=0
    fori=1,#list do
        if list[i-rmCount]==item then
            table.remove(list,i - rmCount)
            if removeAll then
                rmCount=rmCount+1
            else
                break
            end
        end
    end
end
for k,v in pairs(remove) do
    table.removeItem(test,k)
end

猜你喜欢

转载自blog.csdn.net/qq_28098067/article/details/80118384
LUA