Only loop through parts of a table

What is the best way to only loop half of a table. No, not every second value, but from the middle of the table. Like so:

table = {1,2,3,4,5,6,7,8}

Starts from 4 and then goes to 8.

I thought of something like this:

Inside the for loop, have an if statement that checks if the index is bigger/smaller than #table/2

Is there any better way?
Thanks!

Since the given table is an array, with a numerical index, using a for loop you can just do this:

local array = {1, 2, 3, 4, 5, 6, 7, 8}

-- Half of the array gives the middle
-- Meaning #array / 2 = 8 / 2 = 4
-- Note:  odd numbers will require rounding (to give an integer)

local startPosition = #array / 2

for i = startPosition, #array do
	print(array[i])
end
3 Likes
local Table = {1,2,3,4,5,6,7,8,9,10}

for i = #Table/2, #Table, 1 do
     
end

I think that the best way to do that it’s like that.

local startPosition =  math.ceil(#array / 2)  -- Or use math.floor()

for i = startPosition, #array do
	print(array[i])
end

:wink:

Both return integers however, I belive, floor() rounds down where as ceil() rounds up.

local x = 3.5

print(math.floor(x)) -- Rounds down (prints 3)
print(math.ceil(x)) -- Rounds up (prints 4)
1 Like