Log In  

I need to know the size of a table (array) and can't seem to figure out how, shy of just looping through and making my own counter.

I looked up the Lua function and its something like: table.getn(mytable)

But when I try that in P8, it says 'table' doesn't exist, so I'm guessing that part of Lua isn't baked into P8.

So, just wondering if there's a nice way to get the size, or if I just have to write my own function to handle that.

P#20260 2016-05-06 22:43 ( Edited 2016-05-10 19:20)

If you are using tables with the add and del functions, "#yourtable" will give you your table's length!

P#20261 2016-05-06 22:46 ( Edited 2016-05-07 02:46)

Sub-question...what's the best way to delete a table element by index?

The del() looks to only remove an item based on value.

I have a table that contains all items on the screen, but then when that item gets collected by the player, it needs to get removed from the table.

P#20263 2016-05-06 22:52 ( Edited 2016-05-07 02:52)

@T_Dog - Thanks, I didn't know the # syntax...I'll look that up and see what else I can learn.

P#20264 2016-05-06 22:55 ( Edited 2016-05-07 02:55)

You can delete an item by index with "table[index]=nil", but unlike del() this will not reorder the following indexes, so it will leave a hole in the table.

You could then manually reorder by looping over the following indexes and shifting them down, or - if you don't need to preserve table order - just grab the last item in the table and plug it into the hole.

P#20274 2016-05-07 05:53 ( Edited 2016-05-07 09:53)

@Viggles - Gotcha, thanks...good idea about plugging the hole. Array order isn't important so that sounds like a good solution. Although also just checking for nil in whatever routine loop is a doable thing too.

P#20280 2016-05-07 09:23 ( Edited 2016-05-07 13:23)

Rather than looping over the table by index, you can use "for item in all(table) do" or "for index, item in pairs(table) do" to iterate over every item in the table. These will skip over any holes in the indexes and mean that you won't need to care about table length for the loop. You can still safely delete items from within such a loop.

P#20282 2016-05-07 11:15 ( Edited 2016-05-07 15:15)

[Please log in to post a comment]