Reputation: 11
I am trying to make a chess game in love2D, and I am presently trying to generate 8 black pawns in the 7th row, but they all end up in at the last spot of the row.
A picture of (seemingly) 1 pawn in the 7H position on a chess board:
I wrote a for loop as shown below:
for i = 1, 8, 1 do
local column = string.char(64+i)
_G["pawn7"..column] = Pawn:new(0, i, 2)
print(pawn7A.x)
end
Now, I expected the following code to create a global variable of pawn7(A, B, C...etc) with the y value = 2 and an x value = i before repeating the loop. It does function in this way, but it also changes the x value of every pawn generated before the present loop and makes its x = to the current i. This causes all of the stacked pawns as described above. My question is, does setting the variable of x = i normally cause it to change whenever i changes (i didn't think so), and if so how can I avoid this so all my pawns print in the respective spot?
-- Update Okay, so after rewriting my code to be a minimal reproducible example, I replaced the bit that uses the object library with a function that returns a table with its inputs. I also swapped from using the global table to a local table, and that seemed to fix the issue.
pieces = {}
function newPiece(c, x, y)
self = {}
self.c = c
self.x = x
self.y = y
return self
end
for i = 1, 8, 1 do
local column = string.char(64+i)
pieces["p7"..column] = newPiece(0, i, 2)
end
print(pieces.p7A.x)
Upvotes: 1
Views: 60