How to return to the previous value of a table

i want to do the following:

local cosa = {}
for i, cosas in pairs(game.ReplicatedStorage.xd) do
 table.insert(cosa, cosas)
end

After having all that table organized I want that when a function is triggered which will take the parameter: (Forward, Back) if it is before I want it to choose the next one in the table but if it is behind then it chooses the previous one in the table

the script has nothing to do with my game (the theme)