Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
8
Task/Compound-data-type/Lua/compound-data-type-1.lua
Normal file
8
Task/Compound-data-type/Lua/compound-data-type-1.lua
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
a = {x = 1; y = 2}
|
||||
b = {x = 3; y = 4}
|
||||
c = {
|
||||
x = a.x + b.x;
|
||||
y = a.y + b.y
|
||||
}
|
||||
print(a.x, a.y) --> 1 2
|
||||
print(c.x, c.y) --> 4 6
|
||||
9
Task/Compound-data-type/Lua/compound-data-type-2.lua
Normal file
9
Task/Compound-data-type/Lua/compound-data-type-2.lua
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
cPoint = {} -- metatable (behaviour table)
|
||||
function newPoint(x, y) -- constructor
|
||||
local pointPrototype = {} -- prototype declaration
|
||||
function pointPrototype:getX() return x end -- public method
|
||||
function pointPrototype:getY() return y end -- public method
|
||||
function pointPrototype:getXY() return x, y end -- public method
|
||||
function pointPrototype:type() return "point" end -- public method
|
||||
return setmetatable(pointPrototype, cPoint) -- set behaviour and return the pointPrototype
|
||||
end--newPoint
|
||||
9
Task/Compound-data-type/Lua/compound-data-type-3.lua
Normal file
9
Task/Compound-data-type/Lua/compound-data-type-3.lua
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
local oldtype = type; -- store original type function
|
||||
function type(v)
|
||||
local vType = oldtype(v)
|
||||
if (vType=="table" and v.type) then
|
||||
return v:type() -- bypass original type function if possible
|
||||
else
|
||||
return vType
|
||||
end--if vType=="table"
|
||||
end--type
|
||||
14
Task/Compound-data-type/Lua/compound-data-type-4.lua
Normal file
14
Task/Compound-data-type/Lua/compound-data-type-4.lua
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
function cPoint.__add(op1, op2) -- add the x and y components
|
||||
if type(op1)=="point" and type(op2)=="point" then
|
||||
return newPoint(
|
||||
op1:getX()+op2:getX(),
|
||||
op1:getY()+op2:getY())
|
||||
end--if type(op1)
|
||||
end--cPoint.__add
|
||||
function cPoint.__sub(op1, op2) -- subtract the x and y components
|
||||
if (type(op1)=="point" and type(op2)=="point") then
|
||||
return newPoint(
|
||||
op1:getX()-op2:getX(),
|
||||
op1:getY()-op2:getY())
|
||||
end--if type(op1)
|
||||
end--cPoint.__sub
|
||||
7
Task/Compound-data-type/Lua/compound-data-type-5.lua
Normal file
7
Task/Compound-data-type/Lua/compound-data-type-5.lua
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
a = newPoint(1, 2)
|
||||
b = newPoint(3, 4)
|
||||
c = a + b -- using __add behaviour
|
||||
print(a:getXY()) --> 1 2
|
||||
print(type(a)) --> point
|
||||
print(c:getXY()) --> 4 6
|
||||
print((a-b):getXY()) --> -2 -2 -- using __sub behaviour
|
||||
Loading…
Add table
Add a link
Reference in a new issue