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.



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


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.


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


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.


@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.


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.



[Please log in to post a comment]