我们知道lua中没有数组的概念,全都是table,table里面套table,来实现二维数组。
最近就遇到一个问题:
local list ={}
list[1][2] = 3
list[1][3] = 4
list[5][6] = 2
list[5][7] = 8
list[5][9] = 9
list[6][4] = 3
list[9][5] = 3
function hasvalue(p1,p2)
if list[p1][p2] ~= nil then
return list[p1][p2]
end
return -1
end
这看起来很说的通,在list中有这个二维索引的值就返回这个值,但是偶然的发现,hasvalue(4,3)也返回了一个 正确的值,使用type查看类型发现,type(list[4]) 是nil,但是 type(list[4][3])确实是有值的,需要改成
function hasvalue(p1,p2)
if list[p1]~=nil and list[p1][p2] ~= nil then
return list[p1][p2]
end
return -1
end
如此才行。