Latest web development tutorials

Lua 元表(Metatable)

在Lua table 中我們可以訪問對應的key來得到value值,但是卻無法對兩個table 進行操作。

因此Lua 提供了元表(Metatable),允許我們改變table的行為,每個行為關聯了對應的元方法。

例如,使用元表我們可以定義Lua如何計算兩個table的相加操作a+b。

當Lua試圖對兩個表進行相加時,先檢查兩者之一是否有元表,之後檢查是否有一個叫"__add"的字段,若找到,則調用對應的值。 "__add"等即時字段,其對應的值(往往是一個函數或是table)就是"元方法"。

有兩個很重要的函數來處理元表:

  • setmetatable(table,metatable):對指定table設置元表(metatable),如果元表(metatable)中存在__metatable鍵值,setmetatable會失敗。
  • getmetatable(table):返回對象的元表(metatable)。

以下實例演示瞭如何對指定的表設置元表:

mytable = {}                          -- 普通表 
mymetatable = {}                      -- 元表
setmetatable(mytable,mymetatable)     -- 把 mymetatable 设为 mytable 的元表 

以上代碼也可以直接寫成一行:

mytable = setmetatable({},{})

以下為返回對像元表:

getmetatable(mytable)                 -- 这回返回mymetatable

__index 元方法

這是metatable 最常用的鍵。

當你通過鍵來訪問table 的時候,如果這個鍵沒有值,那麼Lua就會尋找該table的metatable(假定有metatable)中的__index 鍵。 如果__index包含一個表格,Lua會在表格中查找相應的鍵。

我們可以在使用lua 命令進入交互模式查看:

$ 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

如果__index包含一個函數的話,Lua就會調用那個函數,table和鍵會作為參數傳遞給函數。

__index 元方法查看表中元素是否存在,如果不存在,返回結果為nil;如果存在則由__index 返回結果。

mytable = setmetatable({key1 = "value1"}, {
  __index = function(mytable, key)
    if key == "key2" then
      return "metatablevalue"
    else
      return nil
    end
  end
})

print(mytable.key1,mytable.key2)

實例輸出結果為:

value1	metatablevalue

實例解析:

  • mytable表賦值為{key1 = "value1"} 。

  • mytable 設置了元表,元方法為__index。

  • 在mytable表中查找key1,如果找到,返回該元素,找不到則繼續。

  • 在mytable表中查找key2,如果找到,返回metatablevalue,找不到則繼續。

  • 判斷元表有沒有__index方法,如果__index方法是一個函數,則調用該函數。

  • 元方法中查看是否傳入"key2" 鍵的參數(mytable.key2已設置),如果傳入"key2" 參數返回"metatablevalue",否則返回mytable 對應的鍵值。

我們可以將以上代碼簡單寫成:

mytable = setmetatable({key1 = "value1"}, { __index = { key2 = "metatablevalue" } })
print(mytable.key1,mytable.key2)

總結

Lua查找一個表元素時的規則,其實就是如下3個步驟:

  • 1.在表中查找,如果找到,返回該元素,找不到則繼續
  • 2.判斷該表是否有元表,如果沒有元表,返回nil,有元表則繼續。
  • 3.判斷元表有沒有__index方法,如果__index方法為nil,則返回nil;如果__index方法是一個表,則重複1、2、3;如果__index方法是一個函數,則返回該函數的返回值。

__newindex 元方法

__newindex 元方法用來對錶更新,__index則用來對錶訪問。

當你給表的一個缺少的索引賦值,解釋器就會查找__newindex 元方法:如果存在則調用這個函數而不進行賦值操作。

以下實例演示了__newindex 元方法的應用:

mymetatable = {}
mytable = setmetatable({key1 = "value1"}, { __newindex = mymetatable })

print(mytable.key1)

mytable.newkey = "新值2"
print(mytable.newkey,mymetatable.newkey)

mytable.key1 = "新值1"
print(mytable.key1,mymetatable.key1)

以上實例執行輸出結果為:

value1
nil	新值2
新值1	nil

以上實例中表設置了元方法__newindex,在對新索引鍵(newkey)賦值時(mytable.newkey = "新值2"),會調用元方法,而不進行賦值。 而如果對已存在的索引鍵(key1),則會進行賦值,而不調用元方法__newindex。

以下實例使用了rawset 函數來更新表:

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)

以上實例執行輸出結果為:

new value	"4"

為表添加操作符

以下實例演示了兩表相加操作:

-- 计算表中最大值,table.maxn在Lua5.2以上版本中已无法使用
-- 自定义计算表中最大值函数 table_maxn
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

-- 两表相加操作
mytable = setmetatable({ 1, 2, 3 }, {
  __add = function(mytable, newtable)
    for i = 1, table_maxn(newtable) do
      table.insert(mytable, table_maxn(mytable)+1,newtable[i])
    end
    return mytable
  end
})

secondtable = {4,5,6}

mytable = mytable + secondtable
	for k,v in ipairs(mytable) do
print(k,v)
end

以上實例執行輸出結果為:

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

__add 鍵包含在元表中,並進行相加操作。 表中對應的操作列表如下:

模式 描述
__add 對應的運算符'+'.
__sub 對應的運算符'-'.
__mul 對應的運算符'*'.
__div 對應的運算符'/'.
__mod 對應的運算符'%'.
__unm 對應的運算符'-'.
__concat 對應的運算符'..'.
__eq 對應的運算符'=='.
__lt 對應的運算符'<'.
__le 對應的運算符'<='.

__call 元方法

__call 元方法在Lua 調用一個值時調用。 以下實例演示了計算表中元素的和:

-- 计算表中最大值,table.maxn在Lua5.2以上版本中已无法使用
-- 自定义计算表中最大值函数 table_maxn
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

-- 定义元方法__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))

以上實例執行輸出結果為:

70

__tostring 元方法

__tostring 元方法用於修改表的輸出行為。 以下實例我們自定義了表的輸出內容:

mytable = setmetatable({ 10, 20, 30 }, {
  __tostring = function(mytable)
    sum = 0
    for k, v in pairs(mytable) do
		sum = sum + v
	end
    return "表所有元素的和为 " .. sum
  end
})
print(mytable)

以上實例執行輸出結果為:

表所有元素的和为 60

從本文中我們可以知道元表可以很好的簡化我們的代碼功能,所以了解Lua 的元表,可以讓我們寫出更加簡單優秀的Lua 代碼。