Lua table中安全移除元素的方法
在Lua中,table如何安全的移除元素這點(diǎn)挺重要,因?yàn)槿绻恍⌒模瑫?huì)沒有正確的移除,造成內(nèi)存泄漏。
引子
比如有些朋友常常這么做,大家看有啥問題
將test表中的偶數(shù)移除掉
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é)果:
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!
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 從后往前刪除
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刪除
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
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)
- 深入談?wù)刲ua中神奇的table
- Lua Table轉(zhuǎn)C# Dictionary的方法示例
- Lua中設(shè)置table為只讀屬性的方法詳解
- Lua編程示例(一):select、debug、可變參數(shù)、table操作、error
- 舉例講解Lua中的Table數(shù)據(jù)結(jié)構(gòu)
- Lua的table庫函數(shù)insert、remove、concat、sort詳細(xì)介紹
- C++遍歷Lua table的方法實(shí)例
- Lua中釋放table占用內(nèi)存的方法
- Lua中table的遍歷詳解
- Lua中獲取table長(zhǎng)度問題探討
- Lua中獲取table長(zhǎng)度的方法
- Lua中table里內(nèi)嵌table的例子
- Lua面向?qū)ο缶幊讨A(chǔ)結(jié)構(gòu)table簡(jiǎn)例
相關(guān)文章
Lua教程(六):綁定一個(gè)簡(jiǎn)單的C++類
這篇文章主要介紹了Lua教程(六):綁定一個(gè)簡(jiǎn)單的C++類,本文是最后一篇C/C++與Lua交互的教程,其他教程請(qǐng)參閱本文下方的相關(guān)文章,需要的朋友可以參考下2014-09-09
lua開發(fā)中實(shí)現(xiàn)MVC框架的簡(jiǎn)單應(yīng)用
最近的游戲項(xiàng)目中使用了lua腳本來開發(fā),項(xiàng)目中用到了MVC框架,最近有朋友問我怎么弄,在這里簡(jiǎn)單分享一下思路和一些開發(fā)中的技巧。有需要的小伙伴可以參考下。2015-04-04

