Father = { house =1= { car=1}setmetatable -- set son's metatable to father. Print (Son.house)
The result of the output is nil, but if you change the code to
Father = { house =1-- Point Father's __index method to his son = { car =1}setmetatable(son, father)print(son.house)
The result of the output is 1, which matches the expected
This, in conjunction with the above example, explains the meaning of the __index meta-method:
In the above example, When visiting Son.house, there was no House member in son, but Lua then found that son had a meta-table father, and then father was looked up as a meta-table, at which point Lua was not directly looking for a member named House in father, but instead called Father's __index method, if the __index method is nil, then nil is returned, if it is a table (the __index method in the example above is equal to itself, this is the case), then to the __index method refers to the table to find a member named House, so, Finally found the House member.
Note: The __index method can be a table in addition to a function, and if it is a function, the return value of the function is returned when the __index method is called.
Here, a summary of the rules that LUA finds for a TABLE element is actually the following 3 steps:
1. Find in the table, if found, return the element, cannot find then continue
2. Determine if the table has a meta-table, if there is no meta-table, return nil, a meta-table will continue
3. Determine if the meta-table has a __index method, if the __index method is nil, then return nil; If the __index method is a table, repeat 1, 2, 3, or return value of the function if the __index method is a function
Lua Lookup Table element procedure (meta-table, how the __index method works)