Table Index [NEED HELP]

Let’s say I have table of 10 indexes, how to print only 5 indexes?
Lets say i have a table
local tabledata = { “A”, “B”, “C”, “D”, “E”, “F”, “G”, “H”, “I”, “J” }
But i want just to print A-E (5 indexes), how? Thank you.

Make a for loop that goes from 1 to 5 then print the element at the index of the current iteration of the for loop

for i, v in pairs(tabledata) do
    if i <= 5 then
        print(v)
    end
end
1 Like
for i = 1, 5 do
    print(tabledata[i])
end

This is what you would do, the loop goes through each integer starting with 1 and ending with 5.

There are other ways to do this though, like the ones above and below me.

There is a more efficient way to do this.

for i, v in pairs(tabledata) do
   if i > 5 then return end
   print(v)
end

Stops the loop once it reaches a threshold rather than continuing the loop wasting resources and time.

for i, v in ipairs(tabledata) do
if i < 6 then
print(v)
end
end

local Iterated = 0

for _, Index in ipairs(tabledata) do
    if Iterated <= 5 then
        print(Index)
        Iterated += 1
    else
        break
    end
end

task.wait(1)

Hopefully this helps you! :smile:

local tabledata = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"}
print(table.unpack(tabledata, 1, 5))

Use break instead of return because what if there’s code after the for loop you want to run? The return would stop it prematurely.