4 ms·
If you have an array in Lua, which is a table used as a contiguous list of items, this is how you get the number of items: num_items = #my_array Your qual
by tylerneylon 11y ago
If you have an array in Lua, which is a table used as a contiguous list of items, this is how you get the number of items:
num_items = #my_array
Your qualm, apparently, is that this # is not built for all use cases of tables.
In C++, what operator tells you how many instance variables a class has? There is none, because that wouldn't make sense in many use cases. Lua tables, offering prototype-based inheritance, experience a similar conceptual ambiguity in the case where you want to take the length of an object.
Lua has made a design decision that the built-in length operator only works on arrays = tables-used-as-a-list and on strings -- cases without ambiguity. If you want the length operator to make sense for a hash map usage, it's a few extra lines of work for you. It's consistent with the langauge being small and flexible, a theme which Lua embraces with elegance.
- coldtea 11y ago>Your qualm, apparently, is that this # is not built for all use cases of tables. My qualms are multiple: (a) this is an operator when it doesn't need to -- a function would do --, (b) this only works for contiguous list of items. (c) Lua, like PHP and JS, has the same type for "contiguous list of items" and hash tables, not even providing a builtin just for the first and/or the latter (e.g. ES6 now does with "Map"). I can understand the powerful metaprogramming capabilities of tables. I also understand that they are not needed, and are even a hidrance, in the tons of cases where all you want is a simple hashmap or a simple vector that wont change under your feet. >* In C++, what operator tells you how many instance variables a class has?* Nobody said C++ was well designed ever, too.