polserver/testsuite/escript/classes/instance-operators.src

50 lines
1.3 KiB
Text
Raw Permalink Normal View History

2026-08-11 20:39:36 +02:00
// The operators a class instance inherits from struct. A script never holds the class instance
// itself - `this` is a reference too - so every one of these goes through the reference and is
// forwarded on.
class Point()
function Point( this, x := 0 )
this.x := x;
endfunction
function bump( this )
// the same operators work on `this`, which is a reference like any other
this["x"] := this["x"] + 1;
return this.x;
endfunction
endclass
var p := Point( 5 );
print( "typeof: " + TypeOf( p ) );
print( "typeofint: " + TypeOfInt( p ) );
// an instance is always true, even with no members at all
if ( p )
print( "istrue: 1" );
else
print( "istrue: 0" );
endif
print( "member: " + p.x );
print( "subscript: " + p["x"] );
// only by name, a struct has no positions
print( "by index: " + p[1] );
p["x"] := 9;
print( "assigned: " + p.x );
print( "in method: " + p.bump() );
// .+ adds a member and refuses to add it twice, .- removes one, .? answers whether it is there
print( "dotplus: " + ( p.+y ) );
print( "dotplus 2: " + ( p.+y ) );
print( "has y: " + ( p.?y ) );
print( "dotminus: " + ( p.-y ) );
print( "has y now: " + ( p.?y ) );
print( "dotminus 2: " + ( p.-y ) );
var empty := Point();
if ( empty )
print( "empty true: 1" );
else
print( "empty true: 0" );
endif