-
Notifications
You must be signed in to change notification settings - Fork 0
Objects
Objects in Algo are similar to objects in JavaScript, but with a twist. To create a simple object, you do the following:
let x = object
{
//insert your properties here :)
};
Note that defining an object also requires a trailing semicolon, unlike libraries and other braced structs.
Once you've defined an object, you can add properties to it, like so:
let x = object { ... };
x.foo = 3;
x.bar = 2;
If you attempt to access a property that doesn't exist, it will simply return null
. You can also define object properties with the definition of the object, instead of doing it after creation. This is great for objects with known structures.
let x = object
{
let y = 3;
let z = [];
};
print x.y; //3
print x.z; //empty list
You can also define functions within objects, within which you can access the scope of the object, like so.
Note: This object won't be able to be serialized with the json
library until all functions are stripped out.
let x = object
{
let counter = 0;
let increment() =
{
counter++;
}
}
print x.counter; //0
x.increment();
print x.counter; //1
Objects are always mutable, and can have properties added and removed from them using let
and disregard
at any time. You can also serialize and deserialize objects from JSON using the json
standard library! Here's a quick example of that:
import "json";
let x = object
{
let y = [1, 2, 3];
let z = "string!";
};
//serialize
let jsonString = json.make(x);
//deserialize
let x_again = json.parse(jsonString);
Algo (c) Larry Tang, 2019.
Commercial use of Algo must include the LICENSE
file in the same directory as the executable.
Standard Library Documentation: