判断table中是否有数据,也就是判断table是否是{}。 运行下面的程序
local mytable = {}
local mytable2 = {333,"hello",666}
if mytable then
print("mytable is true")
else
print("mytable is false")
end
if mytable2 then
print("mytable2 is true")
else
print("mytable2 is false")
end
运行结果:
之所以mytable会打印true我相信大部分人都知道原因,就是lua的判断条件只有false和nil是 “假” ,其他的都是 “真” 。所以table类型的{}也是 “真” 。
解决方案:用 if next(a) == nil then 这句话就是判断table中的值是不是都是nil,如果有一个值不是nil,那么table就不是空,否则就是空。
如下面程序
local mytable = {}
local mytable2 = {333,"hello",666}
if next(mytable) == nil then
print("mytable is true")
else
print("mytable is false")
end
if next(mytable2) == nil then
print("mytable2 is true")
else
print("mytable2 is false")
end
运行结果: