Home Ask Login Register

Developers Planet

Your answer is one click away!

Parki February 2016

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 wrong?


lhf February 2016

You need to return a value in the metamethod:

return rawget(b,k)

Post Status

Asked in February 2016
Viewed 2,160 times
Voted 5
Answered 1 times


Leave an answer

Quote of the day: live life