Define a primitive data type: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
(→‎{{header|Wren}}: Simplified.)
Line 2,871: Line 2,871:
To do this in Wren, you need to define a new TinyInt class with a suitable constructor and re-implement all the operators which apply to integers, checking (in the case of those that return an integer) that the result is within bounds and throwing an error if it isn't.
To do this in Wren, you need to define a new TinyInt class with a suitable constructor and re-implement all the operators which apply to integers, checking (in the case of those that return an integer) that the result is within bounds and throwing an error if it isn't.


Note that inheriting from the basic types, such as Num, is not recommended.
Note that inheriting from the basic types, such as Num, is not allowed.


The following carries out this procedure for a few basic operations and shows examples of their usage including throwing an out of bounds error on the last one.
The following carries out this procedure for a few basic operations and shows examples of their usage including throwing an out of bounds error on the last one.
Line 2,884: Line 2,884:
n { _n }
n { _n }


+(other) {
+(other) { TinyInt.new(_n + other.n) }
var res = _n + other.n
-(other) { TinyInt.new(_n - other.n) }
*(other) { TinyInt.new(_n * other.n) }
if (res < 1 || res > 10) Fiber.abort("Result must be an integer between 1 and 10.")
return TinyInt.new(res)
/(other) { TinyInt.new((_n / other.n).truncate) }
}

-(other) {
var res = _n - other.n
if (res < 1 || res > 10) Fiber.abort("Result must be an integer between 1 and 10.")
return TinyInt.new(res)
}

*(other) {
var res = _n * other.n
if (res < 1 || res > 10) Fiber.abort("Result must be an integer between 1 and 10.")
return TinyInt.new(res)
}

/(other) {
var res = (_n / other.n).truncate
if (res < 1 || res > 10) Fiber.abort("Result must be an integer between 1 and 10.")
return TinyInt.new(res)
}


==(other) { _n == other.n }
==(other) { _n == other.n }
Line 2,936: Line 2,917:
1 != 2 -> true
1 != 2 -> true
1 + 1 == 2 -> true
1 + 1 == 2 -> true
Result must be an integer between 1 and 10.
Argument must be an integer between 1 and 10.
[./primitive line 11] in +(_)
[./primitive2 line 4] in init new(_)
[./primitive line 48] in (script)
[./primitive2 line 7] in
[./primitive2 line 11] in +(_)
[./primitive2 line 34] in (script)
</pre>
</pre>

{{omit from|6502 Assembly}}
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|68000 Assembly}}