Log In  
Follow
jonasan
:: Unfold ::

Hey All,

First post here after recently picking up and playing with pico-8 (humble bundle). It's rather brilliant I have to say!

I have only been playing around with coding for a couple of months and remain very much a novice, and this is my first time using lua with pico-8.

My question is regarding tables of tables (objects I am spawning in my game), and the deletion of those objects...

Let's say we have the following little program which spawns 5 THINGS, gives them unique names, and then adds them to the list a{}. We then delete the item with NAME=3, and then print some output...

a = {}

for i=1,5 do
    local thing = {}
    thing.name = i
    add(a,thing)
end

for thing in all(a) do
 if thing.name == 3 then
  del(a,thing)
 end
end

for thing in all(a) do
 print(thing.name)
end

print("# = "..#a)
print(a[3])

Output is: 1, 2, 4, 5, # = 4, TABLE

This works fine, and is the standard practice I have been using to remove objects from the master table.

However, let's say I already know which item on the main table (a) that I want to delete by its index, say the third item... i.e. a[3]

What I'd like to be able to do is delete that sub-table from the list without iterating through the list a{} to find it (imagine a{} contains lots of objects!), and instead just delete it directly, i.e.

del(a,[3])

but the del() function does not work in this way, so I have been trying to set the sub-table to NIL by its index in the main table a{} i.e....

-- REPLACE THIS
-- for thing in all(a) do
-- if thing.name == 3 then
--  del(a,thing)
-- end
--end

-- WITH
a[3]=NIL

I don't have any idea if this is the right way to approach this, but it has been producing some confusing results....

a[3]=NIL

produces... 1, 2, 4, 5, #=5, NIL

which as far as I can tell means the third item in a{} is now a non-item (NIL) and will not be processed when I iterate through a{}, and the table a{} still has 5 items.

This is not exactly what I'm looking for, as I was hoping to see the # in a{} go down to 4.

Also.... and this is where I'm really confused... attempting to remove the first or second item, a[1] or a[2], produces similar results.... BUT if I try a[5]=nil, then the output is:

1, 2, 3, 4, #=4, TABLE

... which appears to have done what I wanted??

BUT if I try a[4]=nil .... then I get:

1, 2, 3, #=3, TABLE

which seems to have removed both entries 4 and 5 in the table completely ?!?

So.... I'm guessing there must be a better way to achieve what I'm trying to do that I'm not aware of, so if anyone can tell me what that is that would be great!

...and if anyone can explain what is going on to create the strange results above then .... :)

Sorry if that was a little long-winded, just wanted to try and be clear.

Any input here would be much appreciated.
Thanks!

P#35335 2017-01-09 09:13 ( Edited 2017-01-09 15:48)

Follow Lexaloffle:          
Generated 2022-12-01 02:57:42 | 0.053s | Q:5