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.