Lua Lookup Table element procedure (meta-table, how the __index method works)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.