lua中table如何安全移除元素

2021-07-11 02:13:48 字數 2014 閱讀 6788

lua中table如何安全移除元素

ay 20, 2014 | 4 comments

在lua中,table如何安全的移除元素這點挺重要,因為如果不小心,會沒有正確的移除,造成記憶體洩漏。

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

將test表中的偶數移除掉

local

test

=fori,

vinipairs

(test)do

ifv%2

==0then

table.remove

(test,i

)end

endfori,

vinipairs

(test)do

print(i

.."===="..v

)end

列印結果:

1

====32

====83

====94

====205

====136

====157

====78

====11[

finishedin0

.0s]

有問題吧,20怎麼還在?這就是在遍歷中刪除導致的。

let's get started!

local

test

=local

remove

=local

function

dump

(table

)fork,

vinpairs

(table)do

print(k

)print(v

)print

("*********"

)end

end

說明:一般我們不在迴圈中刪除,在迴圈中刪除會造成一些錯誤。這是可以建立乙個remove表用來標記將要刪除的,如上面例子,把將要刪除的標記為true

fori=

#test,1

,-1do

ifremove

[test[i

]]then

table.remove

(test,i

)end

enddump

(test

)

為什麼不從前往後,朋友們可以測試,table.remove操作後,後面的元素會往前移位,這時候後續的刪除索引對應的元素已經不是之前的索引對應的元素了。

locali=

1while

i<=

#test

doif

remove

[test[i

]]then

table.remove

(test,i

)elsei=

i+1end

enddump

(test

)

function

table

.removeitem

(list

,item

,removeall

)local

rmcount=0

fori=1

,#list

doif

list[i

-rmcount]==

item

then

table.remove

(list,i

-rmcount)if

removeall

then

rmcount

=rmcount+1

else

break

endend

endend

fork,v

inpairs

(remove)do

table

.removeitem

(test,k

)end

dump

(test

)

lua遍歷table中刪除table中元素

很多時候,我們有這樣的需求 刪除table中若干符合條件的元素,最原始的想法就是用for遍歷一邊table,符合條件的用table.remove就可以了 function test1 t for i v in ipairs t do if v.id 3 0 then table.remove t i...

在lua中如何remove掉table裡面的資料

在lua開發中,資料儲存一般都會用tabel來儲存,但是在用到table之後,我們都會去清理table,那麼我該怎麼做呢?我們會呼叫到table中的remove函式來清理,但是需要注意的是,remove table,pos 刪除在pos位置上的元素,後面的元素會向前一棟,然後刪除的index會向前移...

lua中設定唯讀table

c 裡有const用來定義常量,保護引數或函式意外地修改,提高程式的健壯性。在lua裡雖然沒有沒有類似的關鍵字,我們可以用表來模擬實現其唯讀的功能,來保護我們的資料被意義地修改。lua 裡有乙個 index metamethod,當我們訪問乙個表不存在的域時,會觸發lua直譯器去查詢 index m...