Loopin' through functions

You can write your topic however you want, but you need to answer these questions:
Basically, I want to run through multiple functions independently and send that data somewhere else. I was wondering if it would be possible to put these functions in a dictionary and use for i,v in pairs, or something similar to loop through them once.

Basically just wondering if it would even be possible and of course, write an example code of it (ONLY if you want) otherwise I’ll write it myself.

Thanks for any input given.

yes I write function libraries often, it is the same notation as a ModuleScript

local funcs = {
   a = function() 
      print("aa") 
   end, 
   b = function() 
      print("bb") 
   end
} 
for _, v in funcs do v() end
funcs.a()
funcs["b"]()

A list can contain any value apart from nil, in it’s keys and it’s values. These could be functions, so yes, you can iterate these and call the functions.

If you’re trying to have the functions run independently, you could loop through a dictionary that contains your functions then spawn a new task for each of them and have then return after they’re done. This is a function that should demonstrate that:

local funcs = {
   a = function()
      return 1+1
   end,
   b = function()
      return “Hello World!”
   end
}

local function CallFuncs()
   local values = {}
   local remaining = 0
   for i,v in pairs(funcs)
      remaining += 1
      task.spawn(function()
         value[i] = v()
         remaining -= 1
      end)
   end

   repeat task.wait() until remaining <= 0
   return values
end

This is a function that calls all the functions stored in the table asynchronously and waits till all of them have returned then returns a table filled with all the values returned from the functions.

You could call this function in a separate thread and send the returned value to something else using something like a bindable event for example:

local Event = *bindable event*
coroutine.resume(coroutine.create(function()
   local values = CallFuncs() — Example Result: {a = 2, b = “Hello World!”}
   Event:Fire(values)
end))

I hope this might have helped!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.