0

I have the following object:

local Game = {}
function Game:new(aNumberOfPlayers, aPlayer1, aPlayer2)
    self.NumberOfPlayers = aNumberOfPlayers
    self.Player1 = aPlayer1
    self.Player2 = aPlayer2
    self.Id = HttpService:GenerateGUID(true)
    self.Status = "Waiting"
    self.Moves = {}
    self.Position = GetInitialGamePosition()
    return self
end

local Square = {}
function Square:new(x, y, index, color)
    self.X = x
    self.Y = y
    self.Index = index
    self.Color = color
    return self
end

That uses following function to intialize the 2d array for Position

function GetInitialGamePosition()
    local mt = {}   -- create the matrix
    for i=1,15 do
        mt[i] = {}
        for j=1,15 do
            mt[i][j] = Square:new(i,j,GetIndexFromRowColumn(i,j),nil)
        end
    end
    return mt
end

Problem here is that since tables pass by reference each element of the 2d array ends up being the same. In other words when i iterate over a Position every element has same row, column, and index. Not sure what the best way to get around this is?

2
  • Which two elements are the same? Commented Oct 3, 2020 at 23:13
  • @ Egor Skriptunoff So the game object ends up with an array with 15 rows and 15 columns which each contain a square object. Each square object has X=15, Y=15, and index of 225. Basically treating row, column, and index as global variables Commented Oct 3, 2020 at 23:23

1 Answer 1

1
function Square:new(x, y, index, color)
    local o = {}
    o.X = x
    o.Y = y
    o.Index = index
    o.Color = color
    setmetatable(o, self)
    self.__index = self
    return o
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.