2

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!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Gamora
  • 337
  • 2
  • 18
  • 1
    Unrelated to the problem: Why not simply return *true* if true and *false* else? – TrebledJ Jul 05 '19 at 11:14
  • There is no problem returning true and false, I was actually converting someone else's code from a DSL into Lua and just kept the conventions. – Gamora Jul 05 '19 at 11:15
  • Related question: [Why does Lua's length (#) operator return unexpected values? - Stack Overflow](https://stackoverflow.com/questions/23590885/why-does-luas-length-operator-return-unexpected-values?noredirect=1) – user202729 Jul 17 '22 at 14:55

1 Answers1

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.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
  • Thanks for your insight Bartek, good to know. Would you mind pointing me in the right direction with implementing that? I'm very new to Lua and very bad with tables! – Gamora Jul 05 '19 at 13:41
  • @Bee In your original question, simply change `return nil` to `return "NoMatch"` or something like that. You just need a non-nil value. You could e.g. define it at the start of your program like `my_nil = { }`, and then by using this you'll only store the reference to that empty table. – Bartek Banachewicz Jul 05 '19 at 13:44
  • Hi Bartek, thanks again, I do understand that bit, I'm not entirely sure how to use ipairs! Either way, you answered my initial question – Gamora Jul 05 '19 at 13:47
  • @Bee I learned about `ipairs` from the excellent Lua [Reference Manual](https://www.lua.org/manual/5.3/manual.html#pdf-ipairs). – Tom Blodget Jul 07 '19 at 02:57
  • @Tom, obviously I have read the full manual and tried using that to create this but was obviously still having issues, hence asking. I have found help elsewhere – Gamora Jul 08 '19 at 09:15