How to move one row of a grid?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
ITISTHEBKID
Prole
Posts: 8
Joined: Sun Nov 11, 2018 9:45 pm

How to move one row of a grid?

Post by ITISTHEBKID »

I have every cell of a grid in a table. How would I go about shifting all the cells over and moving the last row to the first row?
User avatar
pgimeno
Party member
Posts: 3656
Joined: Sun Oct 18, 2015 2:58 pm

Re: How to move one row of a grid?

Post by pgimeno »

It depends. If the purpose is something similar to Netslide, then you would go column by column, and for each column, set a variable to the element in the last row, then loop from the end backwards, setting each element to the previous (you would loop up to 2). Finally, you would set element 1 to the variable you stored.

In code:

Code: Select all

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

local numColumns = 3
local numRows = 3

for column = 1, numColumns do
  local wrappedElement = grid[numRows][column]
  for row = numRows, 2, -1 do
    grid[row][column] = grid[row - 1][column]
  end
  grid[1][column] = wrappedElement
end

for i = 1, numRows do print(unpack(grid[i])) end
--[[
 output:
7	8	9
1	2	3
4	5	6
--]]
For other purposes, you can get away with just using the % operator on the coordinates plus the offsets, but it's hard to give specific advice without more details.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Semrush [Bot] and 2 guests