Random Function

Morning, I’m currently in the process of experimenting with a game, but I need to select a random function from my module script as they’re the equivalent to an event in-game. I’ve looked into dictionaries, but I can’t seem to wrap my head around how you would use functions in them and randomly select one from them.

Here is the script that I tried, obviously, it didn’t work but it’s so you can get the gist of what I’m trying to accomplish:

local GameEvents = {}

local RS = game:GetService("ReplicatedStorage")
local RemoteEvents = RS:WaitForChild("RemoteEvents")
local TextEvent = RemoteEvents:WaitForChild("TextEvent")
local TextInterval = 2
local EventTable = {"ShrinkPlate", "Random"}

-- Event Functions

function GameEvents.ShrinkPlate(player)
	TextEvent:FireAllClients("ShrinkPlate has been chosen")
	local houses = workspace:FindFirstChild("Houses")
	
	for h,house in pairs(houses:GetChildren()) do
		if house:FindFirstChild("HouseOwner") and house:FindFirstChild("HouseOwner").Value == player.Name then
			house.Floor.Size = Vector3.new(house.Floor.Size.X - 10, house.Floor.Size.Y, house.Floor.Size.Z - 10)
			TextEvent:FireAllClients(player.."'s plate has been shrunk by 10 studs!")
			wait(TextInterval)
			TextEvent:FireAllClients("")
		end
	end
end

function GameEvents.Random(player)
	TextEvent:FireAllClients("Random has been chosen")
end

-- Miscellaneous Functions


function GameEvents.RandomEvent()
	local houses = workspace:FindFirstChild("Houses")
	local randomEventNumber = math.random(1,#EventTable)
	local found = false
	local plr = nil
	
	while not found do
		local randomNumber = math.random(1,#houses:GetChildren())
		
		for h,house in pairs(houses:GetChildren()) do
			if randomNumber == h and house:FindFirstChild("HouseOwner") then
				plr = house.HouseOwner.Value
				found = true
			end
		end
	end
	
	for e,event in pairs(EventTable) do
		if randomEventNumber == e then
			GameEvents.event(plr)
		end
	end
end

return GameEvents
local functionDict = {} -- just your function dictionary

function functionDict:KillPlayer(plr)
end
function functionDict:RespawnPlayer(plr)
end


local functionList = {} -- make it a list so you can index the functions with a number

for i, v in next, functionDict do
     functionList[i] = v
end

function callRandomFunction()
    local chosenFunction = functionList[math.random(1, #functionList)]
    chosenFunction()
end
3 Likes
local randomIndex = math.random(1, #EventTable)
local eventName = EventTable[randomIndex]
local eventFunction = GameEvents[eventName]
eventFunction(player)

Both solutions worked perfectly fine, thanks for the responses.