Metatable Index

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")

Ah yes, metatables. I’ll walk you through this one dude :slight_smile:

  • __index is used as a reference when a table does not have a specified index
  • Trying to access house.new in data table does not exist.
  • Putting a table there without the __index makes it redirect to the table, not the function.
  • __index is now used to install house into the metatable as a self-data reference.
1 Like

So, the .__index allows it to search house for the function?

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.

2 Likes

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.

1 Like