-2

Say I have multiple tables in {game} like {bullets}, where {bullets} has multiple tables as found below. How would I iterate through and call all the update functions contained in {game}?
--Below is a simplified example, Assume each table in {bullets} has multiple entries not just update. And that the final code must work in cases like game={bullets,coins,whatever}, each entry being of similar nature to bullets.

game={}
   
game.bullets={{update=function(self) end,...}, {update=function(self) end,...},...}

for obj in all(game) do
  for things in all(obj) do
    things:update() end end

--I'm not sure what I"m doing wrong and whether I even need a double for-loop.
--if bullets wasn't embedded in {game} it would just be:

for obj in all(bullets) do
obj:update()
end

I've also tried:

for obj in all(game.bullets) do
    obj:update()
    end

*correction: this works, the problem I want solved though is to make this work if I have multiple tables like {bullets} in {game}. Thus the first attempt at double iterations which failed. So rather than repeat the above as many times as I have items in {game}, I want to type a single statement.

kite
  • 309
  • 2
  • 12
  • What is `all` in your code? or is it that you dont know what the `pairs` and `ipairs` functions are and that is the answer your looking for? [Programming In Lua: 4.3.5 – Generic for](https://www.lua.org/pil/4.3.5.html) – Nifim May 27 '21 at 04:32

1 Answers1

0

all() isn't a standard function in Lua. Is that a helper function you found somewhere?

Hard to tell without seeing more examples, or documentation showing how it's used, with expected return values. Seems to be an iterator, similar in nature to pairs(). Possibly something like this:

for key, value in pairs( game ) do
    for obj in all( value ) do
        obj :update()
    end 
end
Doyousketch2
  • 2,060
  • 1
  • 11
  • 11
  • as u rightly concluded 'all' is just grabbing each obj in the table. so its equivalent of javascrpt: for (var of arr) {} --for...of loop. Do u kno why the double all loops didnt work tho? – kite May 27 '21 at 04:57
  • its builtin part of pico8's api, i forgot its not native lua. https://wh0am1.dev/pico8-api/ – kite May 27 '21 at 04:59
  • 1
    Oh yea, so it's just `for key, val in pairs(tbl)` but they're throwing out the "key". Normally you'd write that as `for _,v in pairs(t)` and then it's understood that the _ is ignored. Still not entirely certain. https://pico-8.fandom.com/wiki/All If I had to guess, it's getting hung up on a nil or duplicate entry somewhere. `for key, val in pairs(game) do print( type(key), key, type(val), val ) end` I'd imagine those bullets are practically identical. – Doyousketch2 May 27 '21 at 10:42