How to stop nil values in a list being counted

只谈情不闲聊 提交于 2019-12-11 00:56:34

问题


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!


回答1:


# 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.

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



来源:https://stackoverflow.com/questions/56901928/how-to-stop-nil-values-in-a-list-being-counted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!