Parki
Parki

Reputation: 159

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?

Upvotes: 0

Views: 241

Answers (1)

lhf
lhf

Reputation: 72422

You need to return a value in the metamethod:

return rawget(b,k)

Upvotes: 4

Related Questions