The goal of this code is to make a grid that is infinitely large by creating a new row whenever one is asked for (via the __index
metamethod).
When I ask for a row from the board I do get a row, but it doesn't save it -- if I ask for the same row number, I don't get the same row table out.
local board = {}; setmetatable(board, {__index = function(row) local t = {}; board[row] = t; return t; end}); board[0][0] = true; assert(board[0] == board[0], "inconsistent"); -- This assert fails, so that means board[0] is NOT the -- same thing as board[0] -- Why? assert(board[0][0] == true, "(0, 0) not set"); -- (This one also fails, for the same reason, probably)
Code partially works. assert
s fail, but I can't see why.
I'm obviously missing something here.
The problem is super simple: you forgot the first parameter of __index
, the Table being indexed!
Changing line 2 to:
setmetatable(board, {__index = function(_, row)
Fixed the problem for me.
EDIT: For anybody that doesn't understand metamethods, the reason the code didn't actually error is that you can use a Table as an index in Table. Any Table, including itself!
Basically, whenever __index
was invoked, it was setting:
board[board] = t
Instead of the passed-in row.
Locked by User#5978, Marios2, and BlueTaslem
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?