# Loops in Tables

Hello. I have a table, and I want to loop it like that:

Let me explain better. When the event fired, A will be table[3], C will be table[2], and B will be table[1]. And the new situation of the table will be {B,C,A}.

How can I do that? With metatables? Or table functions?

2 Likes

This would be the easy way:

``````local T = {"A","B","C"}
while wait() do
for i = #T,1,-1 do
print(T[i])
end
end
``````

I donâ€™t know what you mean but I know that if you want to make a loop with the table you can use pairs()

Do you want to change the position or want to loop it twice, I donâ€™t get it.

I meant, when the event fired, {A,B,C} will be {B,C,A}. If happens again, then it will be {C,A,B}. Again then {A,B,C}. So, table[index] will change positions with table[index+1] (the next position) if there is not next position(if itâ€™s table[1]), then it will be last table. Example: {A,B,C}, event fired, {B,C,A}. Event fired, {C,A,B}â€¦

Change positions. table[index] to table[index+1](the next position) if its tablr[1], then move to last index. Example: {A,B,C}, event fired: {B,C,A}

If I understand the pattern correctly this might work

``````local function pattern(t)
local first = t[1]
table.remove(t, 1)
table.insert(t, first)
return t
end
``````

Maybe like this:

``````local T = {"A","B","C"}
for i = #T,1,-1 do
local T2 = {}
for _,L in pairs(T) do
if L ~= T[i] then
table.insert(T2,L)
end
end
print(T[i],table.unpack(T2))
end
``````

Another way could be this

``````local function pattern(t)
table.move(t,1,1,4)
table.remove(t,1)
return t
end
``````

Moves a copy of the first thing to the 4th index so it doesnâ€™t overwrite the 3rd and then remove the first thing

Quickly chucked it into an online lua compiler and used it 3 times and gave me this

2 Likes

Umm, this might go kinda off topic but which lua compiler do u use? because I want it too!

I typically just use this for quick compiling without going to roblox https://www.tutorialspoint.com/execute_lua_online.php

Itâ€™ll have problems printing a table as expected, just use an in pairs loop to print the full table

1 Like