Play a Random Function

I Want in my script to be able to run a random function

local bossFunctions = {}
local MethodNames = {}

			bossFunctions.print = function()
				print("1")
			end

			bossFunctions.print2 = function()
				print("2")
			end
		for MethodName, Method in pairs(bossFunctions) do
			if type(Method) == "function" then --make sure that this value is a function
				table.insert(MethodNames, MethodName)
				local RandomMethodName = MethodNames[math.random(1, #MethodNames)]
				local Method = bossFunctions[MethodName]
				Method()
			end
		end

but every time I run (Method) It runs all of them at the same time. Do you have any idea why and where to start to fix it?

2 Likes

You are calling the function inside the loop which will make it run twice. Separating them will print one randomly each time you call the function.

for MethodName, Method in pairs(bossFunctions) do
	if type(Method) == "function" then 
		table.insert(MethodNames, MethodName)
	end
end

local function randomBoss()
	if #MethodNames > 0 then
		local RandomIndex = math.random(1, #MethodNames)
		local RandomMethodName = MethodNames[RandomIndex]
		bossFunctions[RandomMethodName]()

	end
end

randomBoss()
1 Like

I would just do this by the way

local boss_fights = {
	bob = function()
		print("bob")
	end,
	roxy = function()
		print("roxy")
	end
}

local keys = {}
for key in boss_fights, next do
	if type(key) == "function" then
		table.insert(keys, key)
	end
end

local random_key = keys[math.random(1, #keys)]
boss_fights[random_key]()
1 Like

after testing this alot alot, It seems to not work. Whenever I test it, It sends both functions at the same time

Edit: I think this actually has something to do on my end

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