国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > 綜合 > 正文

Lua table中安全移除元素的方法

2024-07-21 23:04:55
字體:
供稿:網(wǎng)友

在Lua中,table如何安全的移除元素這點(diǎn)挺重要,因?yàn)槿绻恍⌒模瑫?huì)沒有正確的移除,造成內(nèi)存泄漏。

引子

比如有些朋友常常這么做,大家看有啥問題

將test表中的偶數(shù)移除掉

復(fù)制代碼 代碼如下:

local test = { 2, 3, 4, 8, 9, 100, 20, 13, 15, 7, 11}
for i, v in ipairs( test ) do
    if v % 2 == 0 then
        table.remove(test, i)
    end
end

 

for i, v in ipairs( test ) do
    print(i .. "====" .. v)
end


打印結(jié)果:
復(fù)制代碼 代碼如下:

1====3
2====8
3====9
4====20
5====13
6====15
7====7
8====11
[Finished in 0.0s]

有問題吧,20怎么還在?這就是在遍歷中刪除導(dǎo)致的。

 

如何做呢?

Let's get started!

 

復(fù)制代碼 代碼如下:

local test = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p' }
local remove = { a = true, b = true, c = true, e = true, f = true, p = true }

 

local function dump(table)
    for k, v in pairs( table ) do
        print(k)
        print(v)
        print("*********")
    end
end


說明:一般我們不在循環(huán)中刪除,在循環(huán)中刪除會(huì)造成一些錯(cuò)誤。這是可以建立一個(gè)remove表用來標(biāo)記將要?jiǎng)h除的,如上面例子,把將要?jiǎng)h除的標(biāo)記為true

 

方法1 從后往前刪除

復(fù)制代碼 代碼如下:

for i = #test, 1, -1 do
    if remove[test[i]] then
        table.remove(test, i)
    end
end

 

dump(test)


為什么不從前往后,朋友們可以測(cè)試,table.remove操作后,后面的元素會(huì)往前移位,這時(shí)候后續(xù)的刪除索引對(duì)應(yīng)的元素已經(jīng)不是之前的索引對(duì)應(yīng)的元素了。

 


方法2 while刪除

復(fù)制代碼 代碼如下:

 local i = 1
while i <= #test do
    if remove[test[i]] then
        table.remove(test, i)
    else
        i = i + 1
    end
end

 

方法3 quick中提供的removeItem

復(fù)制代碼 代碼如下:

 function table.removeItem(list, item, removeAll)
    local rmCount = 0
    for i = 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

dump(test)

 

 
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 绥江县| 绥宁县| 酒泉市| 丹东市| 大关县| 白城市| 都兰县| 漳州市| 于都县| 普定县| 清镇市| 永宁县| 双桥区| 图木舒克市| 道孚县| 彰化市| 冕宁县| 缙云县| 容城县| 昂仁县| 民权县| 巴里| 镇坪县| 临邑县| 温泉县| 辉县市| 龙陵县| 剑川县| 石河子市| 阿尔山市| 巩义市| 河津市| 永吉县| 大兴区| 阿瓦提县| 华容县| 靖宇县| 金沙县| 淮安市| 天全县| 石家庄市|