The silence and cooperation between Lua's __index and __newindex

Source: Internet
Author: User

This article is reproduced in the Stupid Wood blog, hehe, learn from the great God

This article mainly introduces the __index and __newindex in Lua between the silence and cooperation, this article focuses on the relationship between __index and __newindex, the need for friends can refer to the next

Because I do not want to squeeze too much knowledge in an article, so, some of the small points of knowledge gathered in this article bar ~

1. Silence skills--rejection of __index and __newindex effects

Although __index and __newindex are very useful features, sometimes we want to simply call the table or assign a value to the table.

So, what happens now? Reset a meta-table for table? No, it's a bad idea.

So, the thoughtful LUA gives us this kind of invocation, the following code:

The code is as follows:

Local Smartman ={Name="None",} local T1={hehe=123;       }; Local MT={__index=Smartman, __newindex=function (t, K, v) print ("don't assign a value! ");       End} setmetatable (T1, MT); Print (Rawget (T1,"name")); Print (Rawget (T1,"hehe")); Rawset (T1,"name","thief"); Print (t1.name);

The Rawget function can ignore the __index effect of the meta-table and invoke the field purely from the T1.

The first argument to Rawget is the table to invoke, and the second parameter is the field name of the table.

Therefore, by calling T1 's name field through Rawget, only nil is returned, and the Hehe field is called, the value can be obtained correctly.

Similarly, the Rawset function ignores the __newindex effect of the meta-table and assigns values purely to T1.

To see the output:

The code is as follows:

[lua-Print] Nil[lua123[LUA-print] Thieves

Get the Name field, output nil;
Gets the hehe field, output 123;
After modifying the Name field, output "thief"

This is equivalent to T1 there is no __index and __newindex meta-method.
How about this silent skill is very interesting.

2. read-only table

Now, assuming you continue to be a master, you write a very cow function, and then as the main course you are going home every night to see the movie.

So your function has to be handed over to the company of those who just graduated less than 30 to maintain, let them work overtime every day to 6:30 night. (Jor: Hello!) Do you work overtime 6:30? )

However, such a cow function, can not be casually changed by these newcomers, so, in addition to protecting table's meta-table, you also want to protect the table field.

PS: How to protect the meta-table

We can assign a value to the __metatable field of the meta-table, for example: Mt.__metatable = "You don't touch it's meta-table, otherwise after 10 years of probation, you wait to leave!" ”

Then, if the student who is less than 30 is really careless about revising your metatable:

Print (getmetatable (S1));
Setmetatable (S1, MT);

A log similar to the following will be output:

protected metatable

You want to make sure that these newcomers don't change the field value of your table.

Yes, this time you can use __index and __newindex to achieve, the following code:

The code is as follows:

local function readOnly (t) local NewT= {}; Local MT={__index=T, __newindex=function () error ("Don't change me! I'm a read-only! ");    End} setmetatable (NewT, MT); returnnewt;endlocal Days= ReadOnly ({"Monday","Tuesday","Sunday"}); days[2] ="where did you go in Wednesday? ";

This may be a bit difficult to understand, first look at the output:

The code is as follows:

[Lua-print] LUA ERROR: [string"src/main.lua"]:[string ] Src/main.lua "]:don't change me! I'm a read-only!

Yes, the table generated by the ReadOnly cannot be assigned a value operation.

So, what is the principle? Let's think about it a step further:

A. First, ReadOnly will create a new table and then use the table we passed in as the __index meta method.

B. The meta table also adds __newindex, which is used to block assignment operations for fields that do not exist.

The table returned by C.readonly is not our original table, it is an empty table, but it is set up with a new meta-table.

D. Start assignment to days: days[2] = "Wednesday where did it go?" ” 。

E.days is an empty table, so it does not exist in this field, and therefore, the __newindex meta method is called, and the assignment fails.

F. If just call days, do not assign values, such as: print (days[2]); The field value can be output normally, because the meta table of days has a __index meta-method. Although there is no 2 this field in days, this field can be found through __index.

In a word, finally, days becomes a table that can only be read and cannot be assigned.
(Jor: What if I use the Rawset function?) Does it break your limits? )
Cough, we go on.

3. End

Finally ended, these days almost all writing articles, not how to read, but I will continue to write the article ~
After reading the book does not record, always feel not deep enough ~ and finished writing the article mood is very good ~

The silence and cooperation between Lua's __index and __newindex

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.