MetaTable 和 MetaMethod

來源:互聯網
上載者:User

標籤:style   io   color   sp   strong   on   div   cti   bs   

MetaTable:為表元素重載操作符__add(a, b) 對應運算式 a + b__sub(a, b) 對應運算式 a - b

__mul(a, b)                     對應運算式 a * b__div(a, b)                     對應運算式 a / b__mod(a, b)                     對應運算式 a % b__pow(a, b)                     對應運算式 a ^ b__unm(a)                        對應運算式 -a__concat(a, b)                  對應運算式 a .. b__len(a)                        對應運算式 #a__eq(a, b)                      對應運算式 a == b__lt(a, b)                      對應運算式 a < b__le(a, b)                      對應運算式 a <= b__index(a, b)                   對應運算式 a.b__newindex(a, b, c)             對應運算式 a.b = c__call(a, ...)                  對應運算式 a(...)

例:

ta1 = {x = 1, y = 2}
ta2 = {x = 3, y = 4}

--實現tab1+tab2 = {x=4, y=6}

ta = {}
function ta.__add(t1, t2)
temp = {}
temp.x = t1.x + t2.x
temp.y = t1.y + t2.y
return temp
end
setmetatable(ta1, ta)
setmetatable(ta2, ta)
print((ta1+ta2).x, (ta1+ta2).y)

註:setmetatable為lua庫函數,用於重載lua中的操作符

     實現重載的方法(用空表定義,表成員函數)將方法綁定到需要執行的表上

 

   

錯誤認知

ta1 = {x = 1, y = 2, __add}
ta2 = {x = 3, y = 4, __add}

--實現tab1+tab2 = {x=4, y=6}

function add(t1, t2)
temp = {}
temp.x = t1.x + t2.x
temp.y = t1.y + t2.y
return temp
end

ta1._add = add
ta2._add = add
print((ta1+ta2).x, (ta1+ta2).y)

MetaTable 和 MetaMethod

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.