There is a two-dimensional sparse array matrix . Access to the item is as follows:

 if matrix[x] and matrix[x][y] then -- Делаем что-то с этим элементом end 

When using if matrix[x][y] then , if there is no array on X, it gives an error attempt to index a nil value . Is it possible to solve this problem with metatables or by some other option?

  • And what is not satisfied with the preliminary check on matrix[x] ? - zed
  • You have to write the same thing many times. One place I smell that there is a simpler way - Vidoom
  • Then wrap this check into a function. How much easier. - zed

1 answer 1

I can suggest to define a call method for receiving data:

 setmetatable(matrix, { __call = function(self, x, y) result = self[x] == nil if result then return result else return self[x][y] end end, }) 

Now if you need to get the data safely, you can do so.

 content = matrix(x, y) if content then ... end