( LUA ) Timer to Loop All, or just a timer per each.

The title is a little vague, don’t hate. :PP Anyhow…

I was wondering which method is best?




local function RP_TimerFunc_PayDay()
	for i = 1, #player.GetAll() do
		if IsValid(player.GetAll()*) then
			local v = player.GetAll()*
			v:RP_PayDay()
		end
	end
end
timer.Create("RP_TimerHandle_PayDay",600,0,RP_TimerFunc_PayDay)



or this one… I’m also still kind of learning/trying to teaching myself a few things. Just need to know which one would be better for a
populated server. (32 players example.)




local function RP_PD_PlayerSpawn( ply )
    timer.Create("RP.PayDayTimer._"..ply:EntIndex(),600,0,function()
		if IsValid( ply ) then
			ply:RP_PayDay()
		end
    end)
end
hook.Add("PlayerSpawn","RP_PDT.PlayerSpawnHook",RP_PD_PlayerSpawn)



** All help is appreciated! ** :eng101: :eng101: :eng101:

if you’re thinking optimization-wise, and you want to make it as fast as possible, even if it’s a small difference, this is how id go about the first method:



local function RP_TimerFunc_PayDay()
	local players = player.GetAll() -- cache it once instead of doing it each loop

	for i = 1, player.GetCount() do -- player.GetCount is faster than #player.GetAll() (according to the wiki)
		local pl = players*
		if not IsValid(pl) then continue end
		
		pl:RP_PayDay()
	end
end
timer.Create("RP_TimerHandle_PayDay",600,0,RP_TimerFunc_PayDay)


How much faster than player.GetCount() would #players be at that point, though

Legit question

Not very and it’s still faster to use

ipairs.

player.GetCount is slower than counting the player.GetAll table for looping. player.GetCount is only faster when you need the count and not the actual table. Ex.


local tPlayers = player.GetAll()

-- DO:
for i = 1, #tPlayers do
end

-- DON'T:
for i = 1, player.GetCount() do
end

[editline]28th July 2017[/editline]

No, numeric-for loop will always be faster than an iterator.

What makes you think player.GetAll() is faster than player.GetCount in any scenario?

player.GetAll isn’t faster, table counting is faster than player.GetCount. If you’re calling player.GetAll anyway, then you should just count the table.

ye ur right, didn’t think it through :wink:

I was curious on that player.GetCount() and what the real difference was. I just seen that it was supposed to “faster” than player.GetAll() but I didn’t know exactly what for, or how/why the difference is
is.

Anyway, thanks for the help! @Everyone

With lua jit it’s perfectly acceptable to just use ipairs. The speed difference between a for loop and ipairs is often non existent or negligible. It’s more manageable too imo.