Is there a way to call a random function from a table? (ModuleScript)

So, I have a Module Script with a bunch of functions in it and what I want to do is calling a random function from this module

Module script:

local events = {}

events.GrowPlate = function(plate:BasePart)
	
	print("Growing plate")
	
end
events.ShrinkPlate = function(plate:BasePart)
	
	print("Shrinking plate")
	
end

return events

What I want to do is a while loop calling a random function from this table each time it loops

local ServerScriptService = game:GetService("ServerScriptService")

local Events = require(ServerScriptService.Modules.Events)

while wait(1) do
	
	--I need to call the random function here
	
end

I have tried to do math random but it definitely wouldnt work. Even if its not a Module Script I dont think it would work at all

while wait(1) do
	
	Events[math.random(#Events)]
	
end

This is the only solution I have tried so far, as I can’t think of any other way to do it, if anyone knows how I can do it I would appreciate any help.

Try replacing


while wait(1) do
	
	Events[math.random(#Events)]
	
end

With


while wait(1) do
	
	Events[math.random(1, #Events)]
	
end

Also, remember that wait is deprecated and task.wait is the correct syntax now!

2 Likes

It still not works, since I cant get the length of a dictionary :confused:

1 Like

It would probably be a more complex way of doing it than this, so I don’t think this would work nonetheless.

2 Likes

Yea, im aware. Im simply on a phone rn so I dont rlly have time to do that stuff lol

1 Like

While you can’t get the length of a dictionary, you can get the values of that dictionary. Try to fetch the functions of the module script into a different array, then loop that array instead. This may comes with some fallbacks, but this should be a way to iterate a dictionary’s values.

1 Like

Just found a source on what your trying to do im pretty sure!

1 Like

Thats exactly what I wanted to do, thanks! :smiley:

1 Like

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