Search code examples
indexingluametatable

Lua, 2-dim. array metatable getting value when "nil"


local A = {{16},
            {4,10},
            {4,4,6},
            {nil,2,-2,4}} -- nil

local n = #A
local G = {}
local mt = {}
mt.__index = function(self, i)
    -- when it goes throw for-loop it brakes when value in "A" is **nil**
    -- also brakes when i do print(G[4][1])
    self[i] = setmetatable({}, {__index = setmetatable(A[i], {__index = function(s, j) return A[j][i] or 0 end})}) 
    return self[i]
end

setmetatable(G, mt)

print(G[1][3]) -- returns 4
print(G[1][4]) -- returns 0

for j=1, n do
    for i=j, n do
       -- G[i][j] = G[i][j]
       io.write(G[i][j], "; ") -- on i=4 i get error, loops in __index...
    end
end

I am trying to add new table to "G" using __index, I need to get value, even if it's nil, from table A and place it in G. When the value is nil in A table I get an error "stack overflow". Matrix is symmetrical, I flipped the values from vertical to horizontal. I don't know how to fix this.


Solution

  • your __index function is just going to re-invoke the same metamethod - hence the stack overflow. you need to use rawget() a la rawget(rawget(A, j), i)

    I'll leave it as an exercise for the reader to implement appropriate null checks.