# \_\_tostring 元方法
在 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\)。
以下實例演示了如何對指定的表設置元表:
```lua
mytable = {} -- 普通表
mymetatable = {} -- 元表
setmetatable(mytable,mymetatable) -- 把 mymetatable 設為 mytable 的元表
```
以上代碼也可以直接寫成一行:
```lua
mytable = setmetatable({},{})
```
以下為返回對象元表:
```lua
getmetatable(mytable) -- 這回返回mymetatable
```
---
## \_\_index 元方法
這是 metatable 最常用的鍵。
當你通過鍵來訪問 table 的時候,如果這個鍵沒有值,那么Lua就會尋找該table的metatable(假定有metatable)中的\_\_index 鍵。如果\_\_index包含一個表格,Lua會在表格中查找相應的鍵。
我們可以在使用 lua 命令進入交互模式查看:
```lua
> other = { foo = 3 }
> t = setmetatable({}, { __index = other })
> t.foo
3
> t.bar
nil如果__index包含一個函數的話,Lua就會調用那個函數,table和鍵會作為參數傳遞給函數。
```
\_\_index 元方法查看表中元素是否存在,如果不存在,返回結果為 nil;如果存在則由 \_\_index 返回結果。
```lua
mytable = setmetatable({key1 = "value1"}, {
__index = function(mytable, key)
if key == "key2" then
return "metatablevalue"
else
return nil
end
end
})
print(mytable.key1,mytable.key2)
```
實例輸出結果為:
```lua
value1 metatablevalue
```
實例解析:
* mytable 表賦值為**{key1 = "value1"}**。
* mytable 設置了元表,元方法為 \_\_index。
* 在mytable表中查找 key1,如果找到,返回該元素,找不到則繼續。
* 在mytable表中查找 key2,如果找到,返回 metatablevalue,找不到則繼續。
* 判斷元表有沒有\_\_index方法,如果\_\_index方法是一個函數,則調用該函數。
* 元方法中查看是否傳入 "key2" 鍵的參數(mytable.key2已設置),如果傳入 "key2" 參數返回 "metatablevalue",否則返回 mytable 對應的鍵值。
我們可以將以上代碼簡單寫成:
```lua
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 元方法的應用:
```lua
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)
```
以上實例執行輸出結果為:
```lua
value1
nil 新值2
新值1 nil
```
以上實例中表設置了元方法 \_\_newindex,在對新索引鍵(newkey)賦值時(mytable.newkey = "新值2"),會調用元方法,而不進行賦值。而如果對已存在的索引鍵(key1),則會進行賦值,而不調用元方法 \_\_newindex。
以下實例使用了 rawset 函數來更新表:
```lua
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)
```
以上實例執行輸出結果為:
```lua
new value "4"
```
---
## 為表添加操作符
以下實例演示了兩表相加操作:
```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
-- 兩表相加操作
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
```
以上實例執行輸出結果為:
```lua
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 調用一個值時調用。以下實例演示了計算表中元素的和:
```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))
```
以上實例執行輸出結果為:
```lua
70
```
---
---
## \_\_tostring 元方法
\_\_tostring 元方法用于修改表的輸出行為。以下實例我們自定義了表的輸出內容。
```lua
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)
```
以上實例執行輸出結果為:
```lua
表所有元素的和為 60
```
從本文中我們可以知道元表可以很好的簡化我們的代碼功能,所以了解 Lua 的元表,可以讓我們寫出更加簡單優秀的 Lua 代碼。
- 1 Lua介紹及環境
- 2 基本語法
- 3 數據類型
- 4 Lua 變量
- 5 循環
- 6 流程控制
- 7 函數
- 8 運算符
- 9 字符串
- 10 數組
- 11 迭代器
- 12 table
- 13 Lua 模塊與包
- 14 Lua 元表(Metatable)
- 14.1 元表案例
- 15 Lua 協同程序(coroutine)
- 16 Lua 文件IO
- 17 Lua 面向對象
- 17.1 類
- 17.2 繼承
- 17.3 封裝
- 18 Lua 與 Mysql
- 19 Lua 與 redis
- 20 Lua 與 JSON
- 21 Lua 與 http
- 22 Lua 與 Nginx
- 22.1 Nginx_Lua的安裝及環境
- 22.2 ngx_lua API(全表)
- 22.3 常用命令介紹
- 22 Lua 人工智能
- (1) Torch的安裝
- (2)Tensor
- Lua與C混合編程