# 常见的4种形式

for key, value in pairs(tbtest) do
XXX
end

for key, value in ipairs(tbtest) do
XXX
end

for i=1, #(tbtest) do
XXX
end

for i=1, table.maxn(tbtest) do
XXX
end 

• for k,v in pairs(tbtest) do 这种形式的遍历
tbtest = {
[1] = 1,
[2] = 2,
[3] = 3,
[4] = 4,
}

for key, value in pairs(tbtest) do
print(value)
end 

• for k,v in ipairs(tbtest) do 这种形式
tbtest = {
[1] = 1,
[2] = 2,
[3] = 3,
[5] = 5,
}

for k,v in ipairs(tbtest) do
print(v)
end 

local tbtest = {
[2] = 2,
[3] = 3,
[5] = 5,
}

for k,v in ipairs(tbtest) do
print(v)
end 

for k,v in ipairs(tbtest) do 这样的循环必须要求tbtest中的key为顺序的，而且必须是从1开始，ipairs只会从1开始按连续的key顺序遍历到key不连续为止

• 这种遍历里面的'#',作用是取长度
tbtest = {
[1] = 1,
[2] = 2,
[3] = 3,
}
print(#(tbtest)) 

tbtest = {
[1] = 1,
[2] = 2,
[6] = 6,
}
print(#(tbtest)) 

tbtest = {
["a"] = 1,
[2] = 2,
[3] = 3,
}

print(#(tbtest)) 

• table.maxn这种形式,获取的只针对整数的key,字符串的key是没办法获取到的.
tbtest = {
[1] = 1,
[2] = 2,
[3] = 3,
}
print(table.maxn(tbtest))

tbtest = {
[6] = 6,
[1] = 1,
[2] = 2,
}
print(table.maxn(tbtest)) 

tbtest = {
["a"] = 1,
[2] = 2,
[3] = 3,
}
print(table.maxn(tbtest)) 

tbtest = {
["a"] = 1,
["b"] = 2,
["c"] = 3,
}
print(table.maxn(tbtest))
print(#(tbtest)) 

## 删除

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

• 从后往前删.
先构造一个要被删除的数据做key的表
local remove = {
[2] = true,
[4] = true,
[8] = true,
[100] = true,
[20] = true
}
for i = #test , 1 , -1 do
if remove[test[i]] then
table.remove(test,i)
end
end

• while删除
local i = 1
while i <= #test do
if remove[test[i]] then
table.remove(test,i)
else
i = i + 1
end
end
• 其实和while删除比较类似
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

10-25
08-07 1470

10-21 510
08-15 2502
08-03 2万+
08-14 825
04-07 1万+
10-28 164