Lua uses metamethod overload operators for object-oriented processing.

Source: Internet
Author: User
Use point as an Example
Local math = require ("math") local point = {x = 0, y = 0} Point. _ Index = pointfunction point. new (x, y) Local Self = setretriable ({}, point) if (type (x) = "table") then for K, V in pairs (X) do Self [k] = V end elseif (type (x) = "Number" and type (y) = "Number ") then self ['X'] = x self ['y'] = y end return selfend -- add two points to Function Point. _ add (P1, P2) Local P3 = point. new ({x = p1.x + p2.x, y = p1.y + p2.y}) return p3end -- two points subtract Function Point. _ Sub (P1, P2) Return Point. new ({x = p1.x-p2.x, y = p1.y-p2.y}) end -- multiply two points to Function Point. _ MUL (P1, P2) Return Point. new ({x = p1.x * p2.x, y = p1.y * p2.y}) end -- two points divide Function Point. _ Div (P1, P2) Return Point. new ({x = p1.x/p2.x, y = p1.y/p2.y}) end -- equal Function Point. _ eq (P1, P2) return p1.x = p2.x and p1.y = p2.yend -- two points away from Function Point: distance (P2) return math. SQRT (math. pow (self. x-p2.x, 2) + math. pow (self. y-p2.y, 2) endfunction point. _ tostring (P1) Return "x = ".. p1.x .. "Y = ".. p1.yendlocal p1 = point. new () print (P1) Local P2 = point. new (1, 2) print (P2) Local P3 = point. new (P2) print (P3) Local P4 = P2 + p3print (P4) Local P5 = P4-p2print (P5) Local P6 = P4 * p5print (P6) local P7 = P6/p4print (P7) print (P7 = P6) print (P7: distance (P6) print (P7)

Output

x=0 y=0x=1 y=2x=1 y=2x=2 y=4x=1 y=2x=2 y=8x=1 y=2false6.0827625302982x=1 y=2

Lua uses metamethod overload operators for object-oriented processing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.