Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is lua Metatable?

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is lua Metatable". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is lua Metatable".

What is Metatable?

The concept of Metatable in Lua is translated into meta-table in China. The meta-table provides a public entrance to redefine the default behavior of any object (value) in Lua. As with many OO language operator overloads or method overloads. Metatable can bring us a very flexible way of programming.

Specifically, each type of value in Lua has its default operation, for example, numbers can do addition, subtraction, multiplication and division, strings can do concatenation operations, functions can do call operations, and tables can do table item assignment operations. They all follow the default logic of these operations, which can be changed through Metatable. For example, you can define how two tables are added together.

Looking at the simplest example, the addition operation of 2 tables is redefined. In this example, the _ _ addfield of c is rewritten and the Metatable of an is set to c. When performing the addition operation, Lua will first check whether a has Metatable and whether the _ _ addfield exists in Metatable. If it is called, it will check the condition of b (the same as a). If none of them is called, the default addition operation will be called, while table does not define the default addition operation, it will report an error.

-- define 2 tables a = {5 for 6} b = {7 end return op1 end 8}-- use c to do Metatable c = {}-- redefine the addition operation c.__add = function (op1, op2) for _, item in ipairs (op2) do table.insert (op1, item) end return op1 end-- set the Metatable of a to c setmetatable (a, c)-- d is now {5pm 6pm 7pm 8} d = a + b

With a perceptual understanding, let's take a look at the specific characteristics of Metatable.

Metatable is not mysterious, it is just an ordinary table. In the data structure of table, Lua defines many entrances to redefine these operations. They all start with a double underscore and start with a domain called table, such as _ _ add in the above example. When you set Metatable for a value and set the override operation field in Metatable, the custom action of the override is triggered when that value performs the operation. Of course, each operation has a method format signature for each operation. For example, _ _ add will pass in two operands on both sides of the plus sign as parameters and require a return value. Some people compare such behavior to an event, which activates the event custom action when the xx behavior is triggered.

Operations defined in Metatable add, sub, mul, div, mod, pow, unm, concat, len, eq, lt, le, tostring, gc, index, newindex, call...

Any value in Lua has Metatable, and different values can have different Metatable or share the same Metatable, but in the function provided by Lua itself, you are not allowed to change the Metatable of any other type of value except the value of table type, unless you use C extension or other libraries. Setmetatable and getmetatable are a set of methods for manipulating Metatable of type table.

Metatable and object-oriented

Lua is a process-oriented language, but the face-to-object appearance can be simulated by Metatable. The key lies in the domain of _ _ index. He provided the entry of the index value of the table. This is much like rewriting the indexer in C #. When a table wants to index a value, such as table [key], Lua will first look for the value of key in table itself. If there is not and there is a Metatable with a _ _ index attribute in this table, then Lua will look for it according to the function logic defined by _ _ index. Think about it, this is not the core idea of object-oriented inheritance, provides a way to achieve it. There are many ways to realize object-oriented in Lua, but none of them can be achieved without _ _ index.

In this example, I use the way I implement OO in ProgrammingInLua to create a Bird object that can fly. Other bird objects are based on this prototype. Ostrich (ostrich) is a kind of bird but can't fly. It is obvious that Bird and Ostrich have independent states respectively.

Local Bird = {CanFly = true} function Bird:New () local b = {} setmetatable (b, self) selfself.__index = self return b end local Ostrich = Bird:New ()-- Bird.CanFly is true, Ostrich.CanFly is true Ostrich.CanFly = false-- Bird.CanFly is true, Ostrich.CanFly is false

_ _ newindex corresponds to _ _ index and is triggered when an update is made to the key of table. You can use rawset and rawget's key operation on table to skip the triggering of these events.

Call and intercept

It takes a lot of trouble to implement dynamic proxy and AOP in Java and C #. Functions like this are very simple in Lua. Although there are a lot of restrictions, you can still feel the flexibility of Lua. This is the _ _ call operation, which is triggered when the value is called.

Here I make a functional call to a () of type an of table, which triggers _ _ call. Another application example can be found in my other article, implementing the event mechanism in Lua.

A = {} function a:Func () print ("simonw") end c = {} c.__call = function (t,) print ("Start") t.Func () print ("End") end setmetatable (a, c) a ()-- [Start simonw End] Thank you for your reading. This is the content of "what is lua Metatable". After the study of this article, I believe you have a deeper understanding of what lua Metatable is. The specific use situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report