Creating not ugly random events

I’m sure everyone at one point in time has made a loop with the ugly

while true do
wait(math.random(1,500))
--wow cool event!!!!!!11!!1
end

My question here is, what exactly is the best way to make an efficient random wait or event that doesn’t look so ugly? Is there a better way? If not, why? I don’t want to make a loop like such, it just doesn’t feel good if you know what I mean.

It doesn’t really get more “efficient” then that.

You could add in better “controlled” randomness which might not look as ugly, for example, every minute have a 1/10 chance of something happening.

local chance = 10 

while true do
    wait(60)
    local c = math.random(1, chance)
    if c == 1 then
         -- Cool event!
    end
end

If you wanted to, for some reason make it look more complicated then it needs to be you could do something like this.

RandomEvent = function()
    wait(math.random(1,500)
    -- Stuff
    RandomEvent() -- Call itself.
end

This will pretty much do the same thing, I’m sure one is slightly better then the other and it’s probably the while true loop, due to it not requiring a global variable. Tbh though, it shouldn’t really matter.

2 Likes
local IntervalMaxMin = {1, 500}
local WaitForEventToFinish = true




local Events = {}
function CreateEvent(Name, Function)
	for i, v in pairs(Events) do
		if v[1] == Name then
			warn("Event Already Exists ("..Name..")")
			return
		end
	end
	table.insert(Events, {
		["Name"] = Name,
		["Function"] = Function
	})
end
local BindableEvent_Set = Instance.new("BindableEvent", script)
BindableEvent_Set.Name = "Set"
BindableEvent_Set.Event:Connect(function(Name, Function)
	CreateEvent(Name, Function)
end)
local BindableEvent_Destroy = Instance.new("BindableEvent", script)
BindableEvent_Destroy.Name = "Destroy"
BindableEvent_Destroy.Event:Connect(function(Name)
	for i, v in pairs(Events) do
		if v[1] == Name then
			table.remove(Events, i)
			return
		end
	end
end)


CreateEvent("E1", function()
	print("E1")
	wait(2)
	print("E1-E")
	return
end)


while wait(math.random(IntervalMaxMin[1], IntervalMaxMin[2])) do
	local Event = Events[math.random(1, #Events)]
	if WaitForEventToFinish then Event["Function"]() else coroutine.wrap(Event["Function"])() end
end

The difference here is you created an array to store the numbers going into the function, in addition to an event system. Thanks for the help!

My apologies, I wrote the title very early in the morning. What I meant to ask was to make it look prettier. I thought about using both the chance and function methods but didn’t know if using either was inefficient or would cause things like memory issues.