I’m having trouble understanding WHY I need __index in this code. I understand that when I try to index something in house it will redirect to… house. But I don’t understand how this helps it find the function.
As my understanding goes:
-home.clean(“now”) is read
-it goes to the home object, which has data
-it can’t find clean, but since there is a setmetatable it then checks house
-but for some reason it can’t find it in house, even though it is there unless I have a __index to redirect it to itself? That’s what I don’t get
local house = {}
--house.__index = house
function house.new(where)
local data = {}
setmetatable(data, house)
return data
end
function house.clean(when)
print'check1'
end
local home = house.new("japan")
home.clean("now")
Yes, but actually no. But still yes. I’ll clarify.
.__index is only called when an index does not exist. __index can be a table, function, or value.
In your case, you try to access “clean” from data. Because it does not exist, it returns the metavalue, which is a table.
If that metavalue has .__index, it will return that. Otherwise, it will return something else.
This is a very specific case, and .__index only has to be used on its self if you are doing imaginary instances, which is your case.
I think I’ve got it now. I think my issue is that I wasn’t understanding that it was returning a table which doesn’t directly have the function in it and therefore by having the __index it allowed it to have access to the function.