pocketlang/tests/lang/class.pk

101 lines
1.7 KiB
Plaintext
Raw Normal View History

2021-06-20 23:28:31 +08:00
2022-04-21 19:53:03 +08:00
class Vec2
def _init(x, y)
self.x = x
self.y = y
end
2021-06-20 23:28:31 +08:00
2022-04-21 19:53:03 +08:00
def add(other)
return Vec2(self.x + other.x,
self.y + other.y)
end
2021-06-20 23:28:31 +08:00
2022-04-21 19:53:03 +08:00
## Note that operator overloading / friend functions
## haven't implemented at this point (to_string won't actually
## override it).
def to_string
return "[${self.x}, ${self.y}]"
end
2021-06-20 23:28:31 +08:00
2022-04-21 19:53:03 +08:00
end
2021-06-20 23:28:31 +08:00
2022-04-21 19:53:03 +08:00
v1 = Vec2(1, 2); assert(v1.x == 1 and v1.y == 2)
print("v1 = ${v1.to_string()}")
v2 = Vec2(3, 4); assert(v2.x == 3 and v2.y == 4)
print("v2 = ${v2.to_string()}")
v3 = v1.add(v2); assert(v3.x == 4 and v3.y == 6)
print("v3 = ${v3.to_string()}")
2022-04-27 22:48:49 +08:00
## Default constructor crash (issue #213)
class A
end
a = A()
print(a)
class B is A
end
b = B()
assert((b is B) and (b is A))
2022-04-27 00:27:35 +08:00
###############################################################################
## INHERITANCE
###############################################################################
class Shape
def display()
return "${self.name} shape"
end
end
class Circle is Shape
def _init(r)
self.r = r
self.name = "circle"
end
def area()
return 3.14 * self.r * self.r
end
end
class Rectangle is Shape
def _init(w, h)
self.w = w; self.h = h
self.name = "rectangle"
end
def area()
return self.w * self.h
end
end
class Square is Rectangle
def _init(w)
## TODO: Currently there is no way of calling super(w, h)
## so we're setting our self here.
self.w = w; self.h = w
self.name = "square"
end
end
c = Circle(1)
assert(c.display() == "circle shape")
assert(c is Circle)
assert(c is Shape)
r = Rectangle(2, 3)
assert(r is Shape)
assert(r.area() == 6)
s = Square(4)
assert(s is Square)
assert(s is Rectangle)
assert(s is Shape)
assert(s.area() == 16)
2022-04-21 19:53:03 +08:00
print('ALL TESTS PASSED')
2021-06-20 23:28:31 +08:00