Search code examples
functionlualua-tablemetatable

How to use __index as a function?


I'm trying to imitate:

b = {1,2,3}
a = setmetatable({1,nil,3},{__index = b})
print(a[2]) -- prints 2

with that:

b = {1,2,3}
a = setmetatable({1,nil,3},{__index = function(t,k) rawget(b,k) end})
print(a[2]) -- nil

What did I do wrong?


Solution

  • You need to return a value in the metamethod:

    return rawget(b,k)