如何在列表中停止nil值 [英] How to stop nil values in a list being counted

查看:70
本文介绍了如何在列表中停止nil值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,如果为true,则返回"Match",否则返回nil.我需要知道列表中"Match"的值的数量(因此在功能中使用nil作为其他值).

I have a function which is returning "Match" if true and nil else. I need to know the number of values in the list which "Match" (hence using nil as the other value in my function).

someList = {"gdj", nil, "jdis"}

print(#someList) --> 3

我的起源问题是在这里,如果没有其他我应该返回的东西!

My origination question is here if there is something I should be returning other than nil!

推荐答案

#运算符的定义很奇怪.它会一直计数到个非null元素中的一个.在您的情况下,它完全有可能也返回1.这是因为 Lua并不真正支持在表中存储nil .

# operator is defined in a rather weird way; it will count until one of non-nil elements. In your case, it's entirely possible that it could return 1 as well. This is because Lua doesn't really support storing nils in tables.

因此,除非您知道表的大小并可以自行停止迭代,否则没有确定的方法可以迭代该表.

As such, there's no definite way to iterate over such a table, unless you know the size of it and can stop the iteration yourself.

最好存储一个专用的"fassy"值,然后使用ipairs手动进行迭代和计数.

It would be much better to store a dedicated "falsy" value, and then simply iterate and count manually using ipairs.

这篇关于如何在列表中停止nil值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆