问题
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