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.
01 | local board = { } ; |
02 | setmetatable (board, { __index = function (row) |
03 | local t = { } ; |
04 | board [ row ] = t; |
05 | return t; |
06 | end } ); |
07 |
08 | board [ 0 ] [ 0 ] = true ; |
09 |
10 | assert (board [ 0 ] = = board [ 0 ] , "inconsistent" ); |
11 | -- This assert fails, so that means board[0] is NOT the |
12 | -- same thing as board[0] |
13 | -- Why? |
14 | assert (board [ 0 ] [ 0 ] = = true , "(0, 0) not set" ); |
15 | -- (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:
1 | 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:
1 | 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?