Return back to 1st value of table

I want to get a specific row of players in a table and return back to the start if table ends.

Example table:

local players = "plr1","plr2","plr3","plr4","plr5","plr6","plr7","plr8","plr9","plr10","plr11","plr12","plr13"

In this table, I want to loop through the players that start from plr5 and then 3 up. So that’ll be plr5, plr6, plr7 and plr8.
The issue arrives when I am nearing the end. Let’s say I start from plr12 and 3 up. So that’ll then be plr12, plr13, nil and nil.

I don’t want it to be nil though, I want it to then return back so it’ll become plr12, plr13, plr1 and plr2

This what I’ve tried so far, but obviously doesn’t work. I just don’t know what else to do.

local players = {"plr1","plr2","plr3","plr4","plr5","plr6","plr7","plr8","plr9","plr10","plr11","plr12","plr13"}

local plrPercentage = #players/100 * 30

local amount = (math.floor(plrPercentage+0.5))
local currentRow = 10

function selectPlayers()
	for plr = currentRow+1, currentRow + amount, 1 do

		print(players[plr])

		if not players[plr] then
			currentRow = 0
		end
	end
	currentRow = currentRow + 1
end

selectPlayers()

I don’t think you can reassign the iterators of a for loop. Make another variable to keep track of the player you’re trying to index. Alternatively use a while loop which would allow you to reassign the condition variable

function selectPlayers()	
	local playerPointer = currentRow +1
	for i = playerPointer, currentRow + amount, 1 do

		if playerPointer >= #players then			
			playerPointer = 1 --Start back over if our index is out of bounds 
		else
			playerPointer += 1
		end	
		print(players[playerPointer])
	end
	currentRow = currentRow + 1
end
1 Like

Wouldn’t it be easier to use a for in pairs loop for this instead of having to calculate rows and amount? I think that’s where your issue lies.
And if you’re trying to do this indefinitely, put that in a while loop.

In addition to what ItsMeKlc has mentioned, you could simplify the code a little by trying this:

function selectPlayers()
	for plr = currentRow+1, currentRow + amount, 1 do

		plr = (plr - 1) % #players + 1 -- Will wrap around if over the limit.
		print(players[plr])

		if not players[plr] then
			currentRow = 0
		end
	end
	currentRow = currentRow + 1
end
1 Like

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