The following Lua code:

define class Cell Cell = {xPos = 0, yPos = 0, …..} local Cells = { {}, {} } function Cell:new (o, xPos, yPos) o = o or {} setmetatable(o, self) self.__index = self self.xPos = xPos self.yPos = yPos …. return o end -- init matrix of cell class instances for i = 1, 10, 1 do Cells[1] = {} for j = 1, 20, 1 do Cells[i][j] = Cell:new(nil, i, j) end end 

As a result of executing this code, the values ​​of the class fields in the matrix are set to the following values:

 Cells[1][1].xPos = 10 Cells[1][1].yPos = 20 … Cells[1][2].xPos = 10 Cells[1][2].yPos = 20 … Cells[10][20].xPos = 10 Cells[10][20].yPos = 20 Но я ожидал такой результат: Cells[1][1].xPos = 1 Cells[1][1].yPos = 1 Cells[1][2].xPos = 1 Cells[1][2].yPos = 2 

What am I doing wrong? I tried different options, but did not get the expected result.

Thanks in advance for the hint

  • Cells[1] = {} - I assume that the index i was thought here, and not one. - aleksandr barakin
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

  1. you have a typo in the line:

     Cells[1] = {} 

    based on the logic of the surrounding structures, instead of 1 should be a variable i .

  2. I, alas, not an expert on lua , so I don’t understand why you need the first argument in the Cell:new function Cell:new , but, in any case, you use the same self variable for all instances created (a similar case is mentioned, for example, this article, as "the naive version of the constructor"). you must either add an assignment at the beginning of this function:

     self = {} 

    or use the variable o instead of self .

full, slightly corrected test (the second option is commented out):

 --define class Cell Cell = {xPos = 0, yPos = 0 } local Cells = { {}, {} } function Cell:new (o, xPos, yPos) o = o or {} -- начало первого варианта реализации self = {} setmetatable(o, self) self.__index = self self.xPos = xPos self.yPos = yPos -- конец первого варианта -- начало второго варианта реализации --[[ setmetatable(o, o) o.__index = o o.xPos = xPos o.yPos = yPos --]] -- конец второго варианта return o end -- init matrix of cell class instances for i = 1, 10, 1 do Cells[i] = {} for j = 1, 20, 1 do Cells[i][j] = Cell:new(nil, i, j) end end -- вывод нескольких элементов for i = 1, 2, 1 do for j = 1, 2, 1 do print ("Cells["..i.."]["..j.."].xPos = "..Cells[i][j].xPos) print ("Cells["..i.."]["..j.."].yPos = "..Cells[i][j].yPos) end end 

returns:

 Cells[1][1].xPos = 1 Cells[1][1].yPos = 1 Cells[1][2].xPos = 1 Cells[1][2].yPos = 2 Cells[2][1].xPos = 2 Cells[2][1].yPos = 1 Cells[2][2].xPos = 2 Cells[2][2].yPos = 2