Detail Lua meta table and meta method _ LuA _ Script home

Detail the meta table and meta method in Lua

Updated: September 11, 2023 08:40:04 Author: Jiang Pengyong
Metatable and Metamethods in Lua are important concepts in the Lua language, they allow us to customize objects and operations, this article gives you a detailed introduction to Lua metatable and metamethods, need friends can refer to the next

First, meta table

The meta table can modify the behavior of a value in the face of an unknown operation, and Lua uses table as the meta table bearer.

Metattables can only give the behavior of a predefined set of operations, which is more restricted than classes and does not support inheritance.

Each value of Lua can have a meta table:

  • Each table and user data type has its own meta table.
  • Values of other types share the same meta table to which the corresponding type belongs.

Second, the setting of the meta table

1, the type of the original metatable

In Lua, the meta table can only be set for table, and other types cannot be set.

The initialization metatable of the table is nil, that is, no metatable is set, only setmetatable can be set, multiple tables can share atable as a metatable (of course, it can also use itself as atable)

Lua initializes the metatable only for string, and that is for all strings, that is, string is the same metatable. The other types are nil.

print(" initial value of table ", getmetatable({})) --> Initial value of table nil print(" initial value of integer ", getmetatable(10)) --> Initial value of integer nil print(" initial value of floating point ", getmetatable(10.0)) --> Initial value of floating point nil -- print to see that the mettable of both strings is the same print(" initial value of string ", getmetatable(" Pengjiang ")) --> Initial value of string table: 0x600000b14640 print(" initial value of string ", getmetatable("jiangpengyong")) --> Initial value of string table: 0x600000b14640 print(" initial value of Boolean ", getmetatable(true)) --> Initial value of Boolean nil print(" initial value of nil ", getmetatable(nil)) --> Initial value of nil nil function sayHello() end print(" initial value of function ", getmetatable(sayHello)) --> Initial value of function nil

2. Set the meta table and obtain the meta table

2-1. setmetatable(table, metatable)

Sets the metatable for the table table

argument

  • table: The table to be set
  • metabale: Meta table. If the value is nil, it indicates that you want to delete the original meta table of the table. If the original meta table has__metatableField, you cannot set the meta table, otherwise an exception will be throwncannot change a protected metatable

__metatable is shared in the Table Dependent Methods section below

Return value:

Returns the table in which the meta table is set, which is the parameter table

2-2. getmetatable(object)

If object does not have a metatable, nil is returned

If the Object object has a metatable and the metatable has a "__metatable" field, the associated value is returned. Otherwise, the metatable of the given Object object is returned

2-3. Give an example

local oriTable = {}
local metaTable = {}
print(setmetatable(oriTable, metaTable), oriTable, metaTable)       --> table: 0x600001ac0840	table: 0x600001ac0840
print(getmetatable(oriTable), metaTable)                            --> table: 0x600001ac0900	table: 0x600001ac0900

For atable with a __metatable field, setting a new metatable raises an exception (see figure below)

t2 = { c = 1 } t2.__metatable = { a = 1 } s1 = {} setmetatable(s1, t2) print('getmetatable(s1)["a"]', getmetatable(s1)["a"]) --> getmetatable(s1)["a"] 1 -- an exception is thrown here: cannot change a protected metatable print(setmetatable(s1, {}))

Third, metatable method

1, have the meta method

The metatable method method is much like the operator method in kotlin

1-1, arithmetic operator

Metatable method implication
__add addition
__mul multiplication
__sub subtraction
__div Division method
__floor floor division
__unm negative
__mod stripping
__pow Power operation
__band Bitwise and
__bor Bitwise OR
__bxor Xor by bit
__bnot Invert by bit
__shl Shift to the left
__shr Shift right
__concat Define the join operator

1-2, relational operator

Metatable method implication
__eq Equal to
__lt Less than
__le Less than or equal to

Note: ~ =, a > b, and a >= b have no corresponding meta-methods and are converted as follows

  • a ~= bWill be converted tonot( a == b)
  • a > bWill be converted tob < a
  • a >= bWill be converted tob <= a

When the relational operator encounters two objects of different types, it simply returns false without searching for any meta-methods

1-3, library related methods

Metatable method implication
__tostring When calledtostringIs checked to see if the value has a meta method__tostring, will be used first.
__metatable The meta table can be protected by using this meta method. Users cannot obtain or modify the meta table. When a mettable has a __metatable field set, getmetatable returns the value of that field, and setmetatable raises an error
__pairs Starting with Lua 5.2, when a meta table has a __pairs meta method, the pairs call that meta method to complete the traversal

1-4. Table related methods

Metatable method implication
__index Once a non-existent field in the table is accessed, nil is normally returned. If this metatable method is set, the __index metamethod corresponding to its own metatable is called, taking the called table (in this case, table, not the metatable) and the key as arguments. It is also possible to set a table to __index, so that the query is directly in the table, which is slightly faster than the method. Can passrawgetGet the raw data, regardless of the meta table.
__newindex When the table is called for index assignment, if the meta table method is set, the called table (that is, table here, not the meta table), key and value are used as parameters to invoke the method. It is also possible to set a table for __newindex to which values are stored directly. Can passrawset(talbe, key, value)Amount totable[key] = valuePerforms a direct assignment to the table, regardless of the meta table.
__len When obtaining the length of the table, this method is invoked to obtain the length

__index__newindexSimilarities and differences

  • Similarities: Both functions are triggered when there is no corresponding key in the table
  • Difference: Called when the index currently required does not have a corresponding value__indexIs called if table is set to a value__newindex

2. Meta method search

If two variables are added, the search rules are as follows:

  • First check whether the first value has a metatable and whether the required metamethod exists. If so, use the metamethod. At this time, the metamethod of the second value is ignored. Otherwise proceed to the next item
  • See if the second value has a metatable and if the required metamethod exists, and use it if so. Otherwise enter article 3
  • Throw exception

3. Give me an example

There are more meta methods here, so don't paste the code, otherwise it will make the article very lengthy. It is recommended that you move to github clone code to run it yourself will be more profound understanding.

The code related to "arithmetic operator", "relational operator", "library related method" can be viewed as follows:

lua: github.com/zincPower/l...

lua: github.com/zincPower/l...

Code associated with Table Dependent methods

Table dependent meta method lua: github.com/zincPower/l...

4. Write last

The above is a detailed explanation of Lua meta table and meta method details, more information about Lua meta table and meta method please pay attention to other related articles Script home!

Related article

  • Lua中的变量和流控制入门学习

    Introduction to variables and flow control in Lua

    This article mainly introduces the variables and flow control in Lua introductory learning, which - two horizontal lines start a single line of comments,- [[plus two [and] indicate multi-line comments -]]], the need of friends can refer to the next
    2015-07-07
  • Lua与C语言间的交互实例

    An example of the interaction between Lua and C

    This article mainly introduces the interaction between Lua and C language examples, this article mainly explains Lua call C language methods and examples, need friends can refer to the next
    2014-12-12
  • Lua中实现面向对象的一种漂亮解决方案

    A beautiful solution for implementing object orientation in Lua

    This article mainly introduces Lua in the implementation of object-oriented a beautiful solution, this article gives the implementation code, the use of methods and code analysis, the need of friends can refer to
    2015-01-01
  • Lua中的变量类型与语句学习总结

    Summary of variable types and statement learning in Lua

    This article mainly introduces the variable types and sentence learning summary in Lua, summarizes some basic knowledge in the process of getting started with Lua, and the friends who need it can refer to it
    2016-06-06
  • 实现Lua中数据类型的源码分享

    Source code sharing of data types in Lua

    There are eight basic types in Lua. Like other dynamic languages, there is no syntax for type definition in the language, and each value carries its own type information. Let's try to see the implementation of the type through Lua 5.2.1 source code
    2015-04-04
  • 把Lua编译进nginx步骤方法

    Compile Lua into the nginx step method

    This article mainly introduces the compilation of Lua into nginx step method, this article explains the operation steps and possible error solutions, need friends can refer to
    2015-06-06
  • lua 基础教程

    lua Basics tutorial

    Lua's syntax is relatively simple and easy to learn, but the features are not weak. So, I just briefly summarize some of Lua's grammar rules, easy to use and easy to check on it. It is estimated that after reading, you will know how to write Lua programs.
    2015-09-09
  • Lua中的基本数据类型详细介绍

    The basic data types in Lua are described in detail

    This article mainly introduces the basic data types in Lua in detail, this article explains the 8 basic data types in Lua in detail, the need for friends can refer to the next
    2014-09-09
  • Lua的编译、执行和调试技术介绍

    Lua compilation, execution and debugging techniques are introduced

    This article mainly introduces the compilation, execution and debugging technology of Lua, this article focuses on the error processing, and also explains the compilation and execution knowledge, the need of friends can refer to the next
    2015-04-04
  • Lua游戏开发教程之时区问题详解

    Lua game development tutorial time zone problem detailed explanation

    Time display problem is the time difference problem, this article mainly introduces you about the Lua game development tutorial of the time zone problem related information, the article through the example code is introduced in great detail, for everyone's study or work has a certain reference learning value, the need for friends below with the small series to learn it
    2018-09-09

Latest comments