Search code examples
functionluapico-8

lua, iterating and calling all same-named-functions of n=3 tiers of tables


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.


Solution

  • 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