4 ms·
If you need something quick-and-dirty, you can maintain an extra `["length"]` field on your table to cache that information. If you want something more polished
by Twisol 8y ago
If you need something quick-and-dirty, you can maintain an extra `["length"]` field on your table to cache that information. If you want something more polished, use a proxy table with custom methods/metamethods mediating access to your array so that the length is properly kept up to date. This isn't terribly different from the situation in C with arrays.
Tables are a basic mechanism for implementing any data structure. That is a qualitatively different statement from saying that tables can replace any data structure. If you need semantics different from what tables immediately provide, you'll need to implement the desired data structure yourself -- but Lua gives you good tools to do that.
> Maybe there’s a better way I don’t know?
You can use `for i, v in ipairs(arr) do ... end` to iterate over an array without worrying about "how far" to iterate. The `ipairs` iterator will determine when it hits the end of the array.
- sulam 8y agoYeah, this is fine until I want the last element of an array. Then I have to iterate it to find it. And writing a loop to get the last element of an array is crazy-town.