lua 判空的坑

在项目中经常会遇到lua判空的情形

local a = {
    
    }
if a then
	print(true)
end

得到的结果
在这里插入图片描述
这样的结果就是a == {}永远返回false,是一个逻辑错误。因为这里比较的是table a和一个匿名table的内存地址

我后面采用的方法是遍历table,用返回的元素个数来判断表是否为空

if #a>0 then
	print(true)
end

但使用# 去遍历元素本身就是带坑的
例如:

local a = {
    
    nil,2,3}
print(#a)

if #a>=3 then
	print(true)
end

在这里插入图片描述
可以清楚的看到# 把nil也算了进去

最后我想到了一个比较靠谱的方法

next(table),利用next函数进行判断。

local a = {
    
    nil,2,3}
print(#a)

if next(a)>=3 then
	print(true)
end

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Brave_boy666/article/details/126450176
LUA