Files
wren/test/api/foreign_class.wren
T

78 lines
1.5 KiB
Plaintext
Raw Normal View History

2015-12-15 16:02:13 -08:00
class ForeignClass {
2015-08-31 21:56:21 -07:00
foreign static finalized
}
2015-08-15 12:07:53 -07:00
// Class with a default constructor.
foreign class Counter {
2015-09-01 08:16:04 -07:00
construct new() {}
2015-08-15 12:07:53 -07:00
foreign increment(amount)
foreign value
}
var counter = Counter.new()
2015-09-15 07:46:09 -07:00
System.print(counter.value) // expect: 0
2015-08-15 12:07:53 -07:00
counter.increment(3.1)
2015-09-15 07:46:09 -07:00
System.print(counter.value) // expect: 3.1
2015-08-15 12:07:53 -07:00
counter.increment(1.2)
2015-09-15 07:46:09 -07:00
System.print(counter.value) // expect: 4.3
2015-08-15 12:07:53 -07:00
// Foreign classes can inherit a class as long as it has no fields.
class PointBase {
inherited() {
2015-09-15 07:46:09 -07:00
System.print("inherited method")
2015-08-15 12:07:53 -07:00
}
}
// Class with non-default constructor.
foreign class Point is PointBase {
construct new() {
2015-09-15 07:46:09 -07:00
System.print("default")
2015-08-15 12:07:53 -07:00
}
construct new(x, y, z) {
2015-11-11 07:55:48 -08:00
System.print("%(x), %(y), %(z)")
2015-08-15 12:07:53 -07:00
}
foreign translate(x, y, z)
foreign toString
}
var p = Point.new(1, 2, 3) // expect: 1, 2, 3
2015-09-15 07:46:09 -07:00
System.print(p) // expect: (1, 2, 3)
2015-08-15 12:07:53 -07:00
p.translate(3, 4, 5)
2015-09-15 07:46:09 -07:00
System.print(p) // expect: (4, 6, 8)
2015-08-15 12:07:53 -07:00
p = Point.new() // expect: default
2015-09-15 07:46:09 -07:00
System.print(p) // expect: (0, 0, 0)
2015-08-15 12:07:53 -07:00
p.inherited() // expect: inherited method
var error = Fiber.new {
class Subclass is Point {}
}.try()
2015-09-15 07:46:09 -07:00
System.print(error) // expect: Class 'Subclass' cannot inherit from foreign class 'Point'.
2015-08-31 21:56:21 -07:00
// Class with a finalizer.
2015-09-01 08:16:04 -07:00
foreign class Resource {
construct new() {}
}
2015-08-31 21:56:21 -07:00
var resources = [
Resource.new(),
Resource.new(),
Resource.new()
]
2015-10-24 10:56:27 -07:00
System.gc()
2015-12-15 16:02:13 -08:00
System.print(ForeignClass.finalized) // expect: 0
2015-08-31 21:56:21 -07:00
resources.removeAt(-1)
2015-10-24 10:56:27 -07:00
System.gc()
2015-12-15 16:02:13 -08:00
System.print(ForeignClass.finalized) // expect: 1
2015-08-31 21:56:21 -07:00
resources.clear()
2015-10-24 10:56:27 -07:00
System.gc()
2015-12-15 16:02:13 -08:00
System.print(ForeignClass.finalized) // expect: 3