Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua Metatable

Lua Metatable

In a Lua table we can access the corresponding key to get the value, but we cannot perform operations (such as addition) on two tables.

Therefore Lua provides metatables, which allow us to change the behavior of a table. Each behavior is associated with a corresponding metamethod.

For example, using metatables we can define how Lua computes the addition operation a+b of two tables.

When Lua tries to add two tables, it first checks whether either of them has a metatable, then checks whether there is a field called __add. If found, it calls the corresponding value. Immediate fields such as __add, and their corresponding values (often a function or a table), are the "metamethods".

There are two very important functions for handling metatables:

The following example demonstrates how to set a metatable for a specified table:

mytable

=

{

}

                         

-- normal table

mymetatable

=

{

}

                     

-- metatable

setmetatable

(

mytable

,

mymetatable

)

   

-- set mymetatable as the metatable of mytable

The above code can also be written in one line:



mytable = setmetatable({},{})

The following returns the metatable of an object:



getmetatable(mytable)                 -- 这会返回 mymetatable


__index metamethod

This is the most commonly used key of a metatable.

When you access a table through a key, if the key has no value, Lua will look for the __index key in the table's metatable (assuming there is a metatable). If __index contains a table, Lua will look up the corresponding key in that table.

We can check in interactive mode by using the lua command:

$ lua

Lua 5

.

3

.

0  Copyright

(

C

)

1994

2015

Lua

.

org

,

PUC

Rio

other

=

{

foo

=

3

}

t

=

setmetatable

(

{

}

,

{

__index

=

other

}

)

t

.

foo

3

t

.

bar

nil

If __index contains a function, Lua will call that function, passing the table and the key as arguments to the function.

The __index metamethod checks whether an element exists in the table. If it does not exist, the result returned is nil; if it exists, the result is returned by __index.

Example

mytable

=

setmetatable

(

{

key1

=

"value1"

}

,

{

  __index

=

function

(

mytable

,

key

)

   

if

key

==

"key2"

then

     

return

"metatablevalue"

   

else

     

return

nil

   

end

 

end

}

)

print

(

mytable

.

key1

,

mytable

.

key2

)

The example output is:



value1    metatablevalue

Example analysis:

We can simply write the above code as:

mytable

=

setmetatable

(

{

key1

=

"value1"

}

,

{

__index

=

{

key2

=

"metatablevalue"

}

}

)

print

(

mytable

.

key1

,

mytable

.

key2

)

Summary

The rules for Lua when looking up a table element are actually the following 3 steps:

  • 1. Look in the table. If found, return the element; if not found, continue
  • 2. Determine whether the table has a metatable. If not, return nil; if it has a metatable, continue.
  • 3. Determine whether the metatable has an __index method. If the __index method is nil, return nil; if the __index method is a table, repeat steps 1, 2, 3; if the __index method is a function, return the function's return value.
  • This part comes from author Huanzi: https://blog.csdn.net/xocoder/article/details/9028347


    __newindex metamethod

    The __newindex metamethod is used to update a table, while __index is used to access a table.

    When you assign a value to a missing index of a table, the interpreter looks for the __newindex metamethod. If it exists, this function is called instead of performing the assignment.

    The following example demonstrates the application of the __newindex metamethod:

    Example

    mymetatable

    =

    {

    }

    mytable

    =

    setmetatable

    (

    {

    key1

    =

    "value1"

    }

    ,

    {

    __newindex

    =

    mymetatable

    }

    )

    print

    (

    mytable

    .

    key1

    )

    mytable

    .

    newkey

    =

    "new value 2"

    print

    (

    mytable

    .

    newkey

    ,

    mymetatable

    .

    newkey

    )

    mytable

    .

    key1

    =

    "new value 1"

    print

    (

    mytable

    .

    key1

    ,

    mymetatable

    .

    key1

    )

    The output of the above example is:

    
    
    value1
    
    nil    新值2
    
    新值1    nil
    
    

    In the above example, the table has the __newindex metamethod set. When assigning to a new index key (newkey), i.e. mytable.newkey = "new value 2", the metamethod is called instead of performing the assignment. However, if assigning to an existing index key (key1), the assignment is performed and the __newindex metamethod is not called.

    The following example uses the rawset function to update the table:

    Example

    mytable

    =

    setmetatable

    (

    {

    key1

    =

    "value1"

    }

    ,

    {

        __newindex

    =

    function

    (

    mytable

    ,

    key

    ,

    value

    )

           

    rawset

    (

    mytable

    ,

    key

    ,

    """

    ..

    value

    ..

    """

    )

       

    end

    }

    )

    mytable

    .

    key1

    =

    "new value"

    mytable

    .

    key2

    =

    4

    print

    (

    mytable

    .

    key1

    ,

    mytable

    .

    key2

    )

    The output of the above example is:

    
    
    new value    "4"
    
    

    Adding operators to tables

    The following example demonstrates the addition operation of two tables:

    Example

    -- custom function table_maxn to compute the maximum key value in a table, i.e., return the table's maximum key value

    function

    table_maxn

    (

    t

    )

       

    local

    mn

    =

    0

       

    for

    k

    ,

    _

    in

    pairs

    (

    t

    )

    do

           

    if

    type

    (

    k

    )

    ==

    "number"

    and

    k

    mn

    then

                mn

    =

    k

           

    end

       

    end

       

    return

    mn

    end

    -- addition operation of two tables

    mytable

    =

    setmetatable

    (

    {

    1

    ,

    2

    ,

    3

    }

    ,

    {

      __add

    =

    function

    (

    mytable

    ,

    newtable

    )

       

    local

    max_key_mytable

    =

    table_maxn

    (

    mytable

    )

       

    for

    i

    =

    1

    ,

    table_maxn

    (

    newtable

    )

    do

         

    table.insert

    (

    mytable

    ,

    max_key_mytable

    i

    ,

    newtable

    [

    i

    ]

    )

       

    end

       

    return

    mytable

     

    end

    }

    )

    secondtable

    =

    {

    4

    ,

    5

    ,

    6

    }

    mytable

    =

    mytable

    secondtable

    for

    k

    ,

    v

    in

    ipairs

    (

    mytable

    )

    do

       

    print

    (

    k

    ,

    v

    )

    end

    The output of the above example is:

    
    
    1    1
    
    2    2
    
    3    3
    
    4    4
    
    5    5
    
    6    6
    
    

    The __add key is contained in the metatable and performs the addition operation. The corresponding list of operations in the table is as follows: (Note:__ is two underscores)

    Mode Description
    __add corresponding operator '+'.
    __sub corresponding operator '-'.
    __mul corresponding operator '*'.
    __div corresponding operator '/'.
    __mod corresponding operator '%'.
    __unm corresponding operator '-'.
    __concat corresponding operator '..'.
    __eq corresponding operator '=='.
    __lt corresponding operator '<'.
    __le corresponding operator '<='.

    __call metamethod

    The __call metamethod is called when Lua calls a value. The following example demonstrates computing the sum of elements in a table:

    Example

    -- compute the maximum value in the table, table.maxn is no longer available in Lua 5.2 and above

    -- custom function table_maxn to compute the maximum key value in a table, i.e., compute the number of elements in the table

    function

    table_maxn

    (

    t

    )

       

    local

    mn

    =

    0

       

    for

    k

    ,

    v

    in

    pairs

    (

    t

    )

    do

           

    if

    mn

    <
    
    k
    
    then
    
    mn
    
    =
    
    k
    
    end
    
    end
    
    return
    
    mn
    
    end

    -- define the metamethod __call

    mytable

    =

    setmetatable

    (

    {

    10

    }

    ,

    {

      __call

    =

    function

    (

    mytable

    ,

    newtable

    )

            sum

    =

    0

           

    for

    i

    =

    1

    ,

    table_maxn

    (

    mytable

    )

    do

                    sum

    =

    sum

    mytable

    [

    i

    ]

           

    end

       

    for

    i

    =

    1

    ,

    table_maxn

    (

    newtable

    )

    do

                    sum

    =

    sum

    newtable

    [

    i

    ]

           

    end

           

    return

    sum

     

    end

    }

    )

    newtable

    =

    {

    10

    ,

    20

    ,

    30

    }

    print

    (

    mytable

    (

    newtable

    )

    )

    The output of the above example is:

    
    
    70
    
    

    __tostring metamethod

    The __tostring metamethod is used to modify the output behavior of a table. In the following example we customize the output content of the table:

    Example

    mytable

    =

    setmetatable

    (

    {

    10

    ,

    20

    ,

    30

    }

    ,

    {

      __tostring

    =

    function

    (

    mytable

    )

        sum

    =

    0

       

    for

    k

    ,

    v

    in

    pairs

    (

    mytable

    )

    do

                    sum

    =

    sum

    v

           

    end

       

    return

    "The sum of all elements in the table is "

    ..

    sum

     

    end

    }

    )

    print

    (

    mytable

    )

    The output of the above example is:

    
    
    表所有元素的和为 60
    
    

    From this article we can know that metatables can greatly simplify our code, so understanding Lua's metatables allows us to write simpler and better Lua code.