Lottery Script Starting multiple times

So I made this shitty lottery ticket script that works perfectly except for one thing, the amount of players on the server is the amount of lotteries it starts and I want it to be only one lottery at a time.

What did I do wrong here?
Do I need to run it on something else than a local server?


hook.Add("PlayerSay" , "LotteryJoinCommand" , function(ply , text)
	if string.lower(text) == "!lottery" or string.lower(text) == "/lottery" or string.lower(text) == "/ticket" or string.lower(text) == "!ticket" then
		if lottery == 1 and ply:PS_GetPoints() > 99 then 
				PrintMessage(HUD_PRINTTALK, "".. ply:Name() .." has bought a lottery ticket for 100 Coins!")
				table.insert( participants, ply )

			elseif #player.GetAll() < 2 then ply:ChatPrint("There are not enough players to start a lottery.")
			elseif ply:PS_GetPoints() > 99 then ply:ChatPrint("The lottery is not active at the moment.")
			elseif ply:PS_GetPoints() < 100 then ply:ChatPrint("You don't have enough Coins to join the lottery.")

if SERVER then

lottery = 0
participants = {}

local function Lottery1()
if #player.GetAll() < 1 then end
	lottery = 1
	table.Empty( participants )
	for k, v in pairs(player.GetAll()) do 
		PrintMessage( HUD_PRINTTALK, "A new lottery has started, type !lottery to join for 100 Coins!" ) v:EmitSound("items/ammocrate_open.wav")

timer.Simple( 5, function()
local w = table.Random( participants ) 
local p = table.Count( participants )
lottery = 0
		for k, v in pairs(player.GetAll()) do 
			if IsValid( w ) then
				PrintMessage( HUD_PRINTTALK, "The lottery has ended, "..w:Name().." won ".. 100*p .." Coins!" ) v:EmitSound("items/ammocrate_close.wav")
				PrintMessage( HUD_PRINTTALK, "The lottery has ended, nobody participated." ) v:EmitSound("items/ammocrate_close.wav")
	timer.Simple( 15, Lottery1 )


timer.Simple( 15, Lottery1 )


Btw im running this in lua/autorun/lottery.lua

Empty your participants table before calling the inner timer.Simple(15, function() …

The closure is getting captured.


Nope, that didn’t fix anything.

Scriptfodder job, pam-pam-paaaaam
When you’re calling loop in the 5 second timer, you ar checking for validity of w, so if player w is valid its looping through all the players.
Now, give me mine $10, because its a five second script and this mistake is ridiculous

Actually the thing that was causing it was the

for k, v in pairs(player.GetAll()) do

and the mistake you made not knowing that is ridiculous.