鍍金池/ 教程/ C/ Lua元表
Lua邏輯運算符
Lua其他運算符
Lua協(xié)同程序
Lua break語句
Lua運算符
Lua面向?qū)ο?/span>
Lua教程
Lua函數(shù)
Lua數(shù)據(jù)庫/MySQL操作
Lua關(guān)系運算符
Lua錯誤處理
Lua數(shù)據(jù)類型
Lua嵌套循環(huán)
Lua變量
Lua基本語法
Lua字符串
Lua for循環(huán)
Lua if語句嵌套
Lua運算符優(yōu)先級
Lua Web編程
Lua while循環(huán)
Lua開發(fā)環(huán)境
Lua if...else語句
Lua標準庫
Lua游戲編程
Lua if語句
Lua算術(shù)運算符
Lua表格
Lua決策
Lua文件I/O
Lua循環(huán)
Lua數(shù)組
Lua元表
Lua repeat...until循環(huán)
Lua迭代器
Lua調(diào)試
Lua模塊
Lua垃圾收集

Lua元表

元表是一個表,有助于改變它連接到一個密鑰集和相關(guān)的元方法的幫助下表的行為。這些元方法是強大的lua功能,如:

  • 更改/添加功能,以運算符表

  • 查看metatables當鑰匙不在使用__index元表中的表可用。

有跡象表明,在處理metatables其中包括使用了兩種重要的方法,

  • setmetatable(table,metatable): 這個方法是用來設(shè)置元表的一個表。

  • getmetatable(table): 此方法用于獲取表的元表。

讓我們先來看看如何設(shè)置一個表作為另一個元表。它如下所示。

mytable = {}
mymetatable = {}
setmetatable(mytable,mymetatable)

上面的代碼可以在一個單一的行被表示為如下所示。

mytable = setmetatable({},{})

__index

元表的查找元表時,它不是在表中提供一個簡單的例子如下所示。

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

print(mytable.key1,mytable.key2)

當我們運行上面的程序,會得到下面的輸出。

value1	metatablevalue

讓解釋發(fā)生了什么事,在上面的例子中的步驟,

  • 該表mytable 這里 {key1 = "value1"}.

  • 元表設(shè)置為mytable中包含一個函數(shù) __index 我們稱之為元方法。

  • 元方法確實仰視的索引“key2”一個簡單的工作,如果找到,則返回“metatablevalue”,否則返回相應(yīng)mytable索引的值。

我們可以有上述程序的簡化版本,如下所示。


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

__newindex

當我們增加__newindex到元表中,如果鍵是沒有在表中可用的,新的鍵的行為將被中繼的方法來定義。一個簡單的示例,其中元表的索引時,索引不是在主表可設(shè)定如下。

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.newkey1)

當運行上面的程序,會得到如下的輸出。

value1
nil	new value 2
new  value 1	nil

可以在上面的程序看,如果一個關(guān)鍵存在于主表,它只是更新它。當一個鍵不可用在maintable,它添加了關(guān)鍵metatable。

該更新用 rawset 函數(shù)相同的表的另一個例子如下所示。

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"

rawset 設(shè)定值,而不使用元表 __newindex。同樣有rawget,獲取的值,而無需使用__index。

表加入操作符的行為

一個簡單的例子結(jié)合使用+運算符的兩個表如下所示。

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密鑰包含在元表中添加操作符+行為。表的鍵和相應(yīng)的操作符如下所示。

            Mode 描述
            __add Changes the behaviour of operator '+'.
            __sub Changes the behaviour of operator '-'.
            上一篇:Lua if語句嵌套下一篇:Lua if...else語句