The Goat Programming Language Reference
Version: 0.3 "Pretty fly".
Copyright © 2017, 2018 Ivan Kniazkov. See license for copying conditions.

Table of contents
1. Introduction
2. Where to download the latest release
3. How to launch Goat script
4. Basics
5. Advanced programming
6. Standard library
7. In comparison with JavaScript
1. Introduction
Goat is a high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language, based on JavaScript. It supports the basic functionality of JavaScript, but in addition, it adds support for multithreading, multiple inheritance, operator overloading (all as in C ++), simplified syntax, and so on.
Why "Goat"? At first, I wanted to name this programming language as "Go", but unfortunately, some little-known company (it seems "Google" or something like that) has already developed a programming language with that name. After a while, when I tried to create the first version of this interpreter on a laptop, lying in a hammock, I was suddenly bitten by my goat. I thought once the name "Go" is occupied, so perhaps the name "Goat" is no worse. I immediately renamed the project folder to this name and since then it has not changed.
2. Where to download the latest release
On GitHub: https://github.com/kniazkov/goat/releases/latest .
3. How to launch Goat script
3.1. Quick start
Just download the executable file, open console, type executable name and specify a script file name as a parameter:
goat.exe program.goat
3.2. Command line parameters
The Goat interpreter parses command line arguments as follows. All arguments started with two hyphens are internal parameters of the interpreter ("options"). The first argument which is not an option is the name of the script file. All next arguments send to script.
For example,
goat.exe --lib=../lib program.goat arg1 arg2
or, the same thing:
goat.exe program.goat --lib=../lib arg1 arg2
or:
goat.exe program.goat arg1 arg2 --lib=../lib
where: goat.exe is Goat executable, program.goat is name of the script, --lib=../lib is option of the interpterer, arg1 and arg2 are arguments of the script.
Here is a list of interpreter options:
--lib
Path (paths) to external libraries (to importable files). For example, a path to the Goat standard library. Several paths can be separated by a semicolon.
goat.exe program.goat --lib=c:\goat\lib;c:\project
Note about path delimiting character, this is most commonly the slash ("/") or the backslash ("\"). While the interpreter parsed paths, it changes delimiting characters to the character used in the current platform. Say, for Windows, all delimiter characters replaced to the backslash, and for Linux (Unix) - to slash. So path --lib=..\folder\lib interpreted as well as path --lib=../folder/lib , for all platforms.
--debug
The Goat interpreter launched in debug mode. It means that interpretation will stop and set step-by-step mode when the interpreter executes debug; statement.
--gc
One of three modes of garbage collection. --gc=serial enable serial mode, it means that the garbage collector periodically stops all threads (but it takes low processor resources for collection and has small memory overhead). --gc=parallel does not stop threads (but it constantly uses some processor resources and also it uses some extra memory), this mode enabled by default. --gc=debug used for debugging purposes for interpreter developer, it calls collector after each statement of a script and this is very slow.
If you don't know what "garbage collection" means, please do not use this parameter, parallel collector is okay for most purposes.
4. Basics
Important note. A significant part of this chapter is the redesigned tutorial from: https://www.w3schools.com/js/default.asp . Since the Goat language is the modified JavaScript language, so the description of the Goat language is the modified description of the Javascript language. Any coincidences are NOT random.
4.1. Hello world
Create a new file, say hello_world.goat (file extension does not matter) containing one line:
print("Hello, world!");
and then launch it:
goat.exe hello_world.goat
That's all. The interpreter will start the script and will print Hello, world! to the console.
4.2. Internationalization and localization
It possible to use any Unicode characters in string literals. The Goat interpreter parses source files in UTF-8 format. Output stream also encoded to UTF-8. The previous example, but contains some "special" symbols:
print("Bonjour, réalité cruelle et ingrate!");
4.3. Program and statements
4.3.1. Program
A computer program is a list of "instructions" to be "executed" by a computer. In a programming language, these programming instructions are called statements.
A Goat program is a list of programming statements.
var x, a, b; // statement 1
a = 2; // statement 2
b = 3; // ... 3
x = a + b; // ... 4
print(x); // ... 5
Goat programs are executed by the Goat interpreter.
4.3.2. Statements
Goat statements are composed of: Values , Operators , Expressions , Keywords , and Comments .
The statements are executed, one by one, in the same order as they are written.
4.3.3. Semicolons
Semicolons ; separate Goat statements. Add a semicolon at the end of each executable statement:
var x, a, b; // declare 3 variables
a = 2; // assign the value 2 to 'a'
b = 3; // assign the value 6 to 'b'
x = a + b; // assign the sum of 'a' and 'b' to 'x'
print(x); // print value of 'x'
When separated by semicolons, multiple statements on one line are allowed:
a = 2; b = 3; x = a + b;
Though ending statements with a semicolon is not required, but highly recommended. This example is correct:
print(2 + 3) // no semicolon at the end
4.3.4. White space
Goat parse tabulations and line breaks as white spaces. Goat ignores multiple spaces. You can add white space to your script to make it more readable. The following statements are equivalent:
var a, b = 0;
var a, b=0;
var a,
  b = 0;
4.3.5. Code blocks
Goat statements can be grouped together in code blocks, inside curly brackets {...} . The purpose of code blocks is to define statements to be executed together. One place you will find statements grouped together in blocks, is in Goat functions:
var f = $(a, b) {
  var x;
  var y;
  x = a + b;
  y = a - b;
  print("summ: " + x + ", diff: " + y);
};
4.3.6. Keywords and keyword sequences
Goat statements often start with a keyword to identify the Goat action to be performed. Here is a list of the keywords (or keyword sequences):
Keyword Description
var Declares a variable
function or $ Declares a function (method)
thread Declares a thread
return Exits a function (method)
if .. else if .. else Marks a block of statements to be executed, depending on a condition
switch ( case , default) Marks a block of statements to be executed, depending on different cases
for ( in ) Marks a block of statements to be executed, as long as a condition is true
while , do .. while Executes a block of statements, and repeats the block, while a condition is true
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
try .. catch .. finally Implements error handling to a block of statements
throw Throws an exception
new Creates a new object
import Imports a source file
debug Stops the execution of Goat script, and switch the interpreter to debug (step-by-step) mode
Goat keywords are reserved words. Reserved words cannot be used as names for variables.
4.4. Syntax
Goat syntax is the set of rules, how Goat programs are constructed:
var a, b, x; // How to declare variables
a = 2; // How to assign values
b = 3;
x = a + b; // How to compute values
print(x); // How to call functions

4.4.1. Values
The Goat syntax defines two types of values: fixed values and variable values. Fixed values are called literals. Variable values are called variables.
4.4.1.1. Literals
The most important rules for writing fixed values are:
Integer numbers are written without decimals:
123
Real numbers are written with decimals, the decimal separator is a dot:
0.001
Strings are text, written within double quotes:
"Hello"
Chars are symbols written within single quotes:
'A'
4.4.1.2. Variables
In a programming language, variables are used to store data values. Goat uses the var keyword to declare variables. An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value 10:
var x;
x = 10;
4.4.2. Operators
Goat uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
Goat uses an assignment operator ( = ) to assign values to variables:
var a, b;
a = 2;
b = 3;
4.4.3. Expressions
An expression is a combination of literals, variables, function calls, other expression and operators, which computes to a value. The computation is called an evaluation. For example, 5 * 10 evaluates to 50:
5 * 10
Expressions can also contain variable values:
x * 2
...or function calls:
x * sin(y)
The values can be of various types, such as numbers and strings:
"Hello" + ", " + "world"
4.4.4. Identifiers
Identifiers are names.
In Goat, identifiers are used to name variables. The rules for legal names are much the same in most programming languages. In Goat, the first character must be a letter or an underscore ( _ ). Subsequent characters may be letters, digits or underscores. Numbers are not allowed as the first character.
4.4.5. Case sensitive
All Goat identifiers are case sensitive. The variables maxValue and maxvalue , are two different variables.
var maxValue, maxvalue;
maxValue = 10;
maxvalue = 0.1;
4.5. Comments
Goat comments can be used to explain Goat code, and to make it more readable. Goat comments can also be used to prevent execution when testing alternative code.
4.5.1. Single line comments
Single line comments start with // . Any text between // and the end of the line will be ignored by Goat (will not be executed). This example uses a single-line comment before each code line:
// Create object:
var obj = {};
// Add a field to the object:
obj.value = 10;
This example uses a single line comment at the end of each line to explain the code:
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
4.5.2. Multi-line comments
Multi-line comments start with /* and end with */ . Any text between /* and */ will be ignored by Goat. This example uses a multi-line comment (a comment block) to explain the code:
/*
The code below declares the function which calculates
and print sum and difference of two arguments
*/
var f = $(a, b) {
  var x;
  var y;
  x = a + b;
  y = a - b;
  print("summ: " + x + ", diff: " + y);
};
4.5.3. Using comments to prevent execution
Using comments to prevent execution of code is suitable for code testing. Adding // in front of a code line changes the code lines from an executable line to a comment. This example uses // to prevent execution of one of the code lines:
var person = {};
person.name = "Ivan";
//person.gender = "Male";
person.age = 33;
This example uses a comment block to prevent execution of multiple lines:
var person = {};
person.name = "Ivan";
/*
person.gender = "Male";
person.age = 33;
*/
4.6. Variables
Goat variables are containers for storing data values. In this example, x , y , and z , are variables:
var x = 5;
var y = 6;
var z = x + y;
4.6.1. Identifiers
All Goat variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y ) or more descriptive names ( age , sum , totalVolume ). The general rules for constructing names for variables (unique identifiers) are:
  • names can contain letters, digits and underscores;
  • names must begin with a letter;
  • names can also begin with _ ;
  • names are case sensitive ( y and Y are different variables);
  • reserved words (like Goat keywords) cannot be used as names.
4.6.2. Data types
Goat can handle many types of data. Goat variables can hold numbers like 100 and text values like "Hello". Basic data types are:
Integer number (without decimal character):
var i = 10;
Real (floating-point) number:
var r = 0.01;
String:
var s = "Hello";
Char (single symbol):
var c = 'A';
And Boolean:
var b = true;
4.6.3. Declaring (creating) Goat variables
Creating a variable in Goat is called "declaring" a variable. You declare a JavaScript variable with the var keyword:
var name;
After the declaration, the variable has no value (technically it has the value of undefined ). To assign a value to the variable, use the equal sign:
name = "Ivan";
You can also assign a value to the variable when you declare it:
var name = "Ivan";
4.6.4. One statement, many variables
You can declare many variables in one statement. Start the statement with var and separate the variables by comma:
var name = "Ivan", age = 33, gender = "male";
A declaration can span multiple lines:
var name = "Ivan",
  age = 33,
  gender = "male";
4.6.5. Undefined
Variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. A variable declared without a value will have the value undefined .
var name; // value of 'name' is undefined
4.6.6. Re-declaring variables
If you re-declare a Goat variable, it will lose its value.
var name = "Ivan";
// do something...
var name; // now, value of 'name' if undefined
4.6.7. Arithmetic
As with algebra, you can do arithmetic with Goat variables, using operators like = and + :
var x = 5 + 2 + 3;
You can also add strings, but strings will be concatenated:
var s = "Hello" + ", " + "world!"
Also try this. The Goat language will convert second operator to string if the first operator is string:
var s = "Value is" + ' ' + 5;
4.7. Operators
4.7.1. Examples
The assignment operator ( = ) assigns a value to a variable.
var x = 10;
The addition operator ( + ) adds numbers:
var a = 2;
var b = 3;
var c = a + b;
The multiplication operator ( * ) multiplies numbers.
var a = 2;
var b = 3;
var c = a * b;
4.7.2. Arithmetic operators
Arithmetic operators are used to perform arithmetic on numbers:
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
++ Increment
-- Decrement
4.7.3. Assignment operators
Assignment operators assign values to Goat variables.
Operator Example Same as
= x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
The addition assignment operator ( += ) adds a value to a variable.
var x = 10;
x += 5;
Value of x will be: 15
4.7.4. String operators
The + and += operators can also be used to add (concatenate) strings.
var a = "Hello";
var b = "world";
var s = a + ", " + b;
Value of s will be: Hello, world!
4.7.5. Adding strings and not-strings
Adding two numbers, will return the sum, but adding a string and a not-string (number, symbol etc) will return a string:
var x = 2 + 3;
var s = "result is: " + x;
Value of s will be: result is: 5
4.7.6. Comparison operators
Operator Description
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
? Ternary operator
4.7.7. Logical operators
Logical operators work with binary ( Boolean ) type.
Operator Description
&& Logical and
|| Logical or
! Logical not
4.7.8. Bitwise operators
Bitwise operators work with Integer type.
Operator Description Example Same as Result Decimal
& And 5 & 1 0101 & 0001 0001 1
| Or 5 | 1 0101 | 0001 0101 5
~ Not ~5 ~0101 ...111010 -6
^ Xor 5 ^ 1 0101 ^ 0001 0100 4
<< Left shift 5 << 1 0101 << 1 1010 10
>> Signed right shift 5 >> 1 0101 >> 1 0010 2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
4.7.9. Special operators
Operator Description
-> Inherit
@ Lock
4.7.10. Common operators
Each object supports these operators: -> (inherit), @ (lock), == (equal), != (not equal) and ! (logical not).
-> (inherit)
Each object can be a prototype for a new object. Below in this document, it will be explained what is prototyping.
@ (lock)
Returns a locked object, that is, an object whose properties can not be changed.
== (equal) and != (not equal)
In common case, an object equals to another object, if these objects are the same object. For numbers, strings, other built-in types, an object is equal to another object if these objects have the same value, for example, 5 == 2 + 3 .
! (not)
In common case, not object is false . The chapters about the comparison and conditions will describe how this is used.
4.8. Arithmetic
4.8.1. Arithmetic Operations
A typical arithmetic operation operates on two numbers. The two numbers can be literals:
var x = 100 + 50;
or variables:
var x = a + b;
or expressions:
var x = (100 + 50) * a;
4.8.2. Operators and operands
The numbers (in an arithmetic operation) are called operands.
The operation (to be performed between the two operands) is defined by an operator.
Operand Operator Operand
100 + 50
If at least one of operators is a real number, the result will be a real number. If both operators are integers, the result will be an integer.
The addition operator ( + ) adds numbers.
var a = 2;
var b = 3;
var c = a + b; // 5
The subtraction operator ( - ) subtracts numbers.
var a = 2;
var b = 3;
var c = a - b; // -1
The multiplication operator ( * ) multiplies numbers.
var a = 2;
var b = 3;
var c = a * b; // 6
The division operator ( / ) divides numbers.
var a = 6;
var b = 2;
var c = a / b; // 3
If at least one of operators is a real number, the Goat interpreter performs real division (for example, 6.0 / 4 = 1.5 ). If both operators are integers, the interpreter performs integer division, i.e. the fractional part of the result will be lost ( 6 / 4 = 1 ).
The modular operator ( % ) returns the division remainder.
var a = 17;
var b = 10;
var c = a % b; // 7
The increment operator ( ++ ) increments numbers.
var a = 2;
a++; // 3
The decrement operator ( -- ) decrements numbers.
var a = 2;
a--; // 1
4.8.3. Operator precedence
Operator precedence describes the order in which operations are performed in an arithmetic expression.
var x = 100 + 50 * 3;
As in traditional mathematics, the multiplication is done first. Multiplication ( * ) and division ( / ) have higher precedence than addition ( + ) and subtraction ( - ).
The precedence can be changed by using parentheses:
var x = (100 + 50) * 3;
When using parentheses, the operations inside the parentheses are computed first.
When many operations have the same precedence (like addition and subtraction), they are computed from left to right:
var x = 100 + 50 - 3;
4.8.4. Operator precedence values
Value Operator Description Example
22 () Expression grouping (3 + 4)
21 . Member person.name
21 [] Member person["name"]
21 ?. Member with void guard person?.name
20 () Function call func()
20 new Create new StringBuilder()
19 ++ Prefix increment ++x
19 -- Prefix decrement --x
18 ++ Postfix increment x++
18 -- Postfix decrement x--
17 ! Logical not !x
16 ~ Bitwise not ~x
15 + Unary plus +x
15 - Unary minus -x
14 -> Inherit A -> { }
13 @ Lock @ { }
12 * Multiplication 10 * 5
12 / Division 10 / 5
12 % Modulo (remainder) 17 % 10
11 + Addition 2 + 3
11 - Subtraction 5 - 2
10 << Shift left x << 2
10 >> Shift right x >> 2
10 >>> Shift right (unsigned) x >>> 2
9 & Bitwise and x & y
8 ^ Bitwise xor x ^ y
7 | Bitwise or x | y
6 < Less than x < y
6 <= Less than or equal x <= y
6 > Greater than x > y
6 >= Greater than or equal x >= y
5 == Equal x == y
5 != Not equal x != y
4 && Logical and x && y
3 || Logical or x || y
2 ? Ternary operator a ? b : c
1 = Assign x = y
1 += Assign by x += y
1 -= Assign by x -= y
1 *= Assign by x *= y
1 /= Assign by x *= y
1 %= Assign by x %= y
1 <<= Assign by x <<= y
1 >>= Assign by x >>= y
1 >>>= Assign by x >>>= y
1 &= Assign by x &= y
1 ^= Assign by x ^= y
1 |= Assign by x |= y
4.9. Assignment
The = assignment operator assigns a value to a variable.
var x = 10; // 10
The += assignment operator adds a value to a variable.
var x = 10;
x += 5; // 15
The -= assignment operator subtracts a value from a variable.
var x = 10;
x -= 5; // 5
The *= assignment operator multiplies a variable.
var x = 10;
x *= 5; // 50
The /= assignment operator divides a variable.
var x = 10;
x /= 5; // 2
The %= assignment operator assigns a remainder to a variable.
var x = 17;
x %= 10; // 7
4.10. Data types
Goat variables can hold many data types: numbers, strings, objects and more:
var length = 16; // Integer
var price = 11.99; // Real
var name = "Ivan"; // String
var obj = {name: "Ivan", age: 33}; // Object
x %= 10; // 7
4.10.1. Concept
In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type.
For example, when adding a number and a something, the Goat interpreter will treat the second operator as a number:
var x = 2 + 3; // result is: 5
But, when adding a string and a something, the Goat interpreter will treat the second operator as a string. If the second operator is not a string, the interpreter will convert it to the string:
var s = "text" + 123; // result is: "text123"
The Goat interpreter evaluates expressions from left to right (but according to precedence). Different sequences can produce different results:
var s1 = "text" + 2 + 3; // result is: "text23"
var s2 = "text" + (2 + 3); // result is: "text5"
4.10.2. Goat types are dynamic
The Goat language has dynamic types. This means that the same variable can be used to hold different data types:
var x; // 'x' is undefined
x = 5; // now 'x' is a integer
x = "Ivan"; // now 'x' is a string
4.10.3. Strings
A string (or a text string) is a series of characters like "Abracadabra". Strings are written with double quotes:
var name="Ivan";
4.10.4. Chars
Char is a single symbol. Chars are written with single quotes:
var c = 'A';
4.10.5. Integers
A number without decimal point:
var i = 10;
4.10.6. Real numbers
A number with decimal point (also, it called "floating-point number"):
var r = 0.01;
4.10.7. Booleans
Booleans can only have two values: true or false :
var t = true;
var f = false;
Booleans are often used in conditional testing:
var x = 5;
var y = 5;
var z = 6;
var t = (x == y); // true
var f = (x == z); // false
4.10.8. Arrays
Goat arrays are written with square brackets. Array items are separated by commas. The following code declares (creates) an array called herd , containing three items (goats nicknames):
var herd = ["Dirty", "Stinky", "Crazy"];
Array indexes are zero-based, which means the first item is [0] , second is [1] , and so on.
4.10.9. Objects
Goat objects are written with curly braces. Object properties are written as name: value pairs, separated by commas.
var goat = { name: "Stinky", wool: Color.WHITE, age: 3};
4.10.10. Undefined
In the Goat language, a variable without a value, has the value undefined .
var name; // value is undefined
Any variable can be emptied, by setting the value to undefined .
name = undefined;
4.10.11. Null
In the Goat language, null is "nothing". It is supposed to be something that doesn't exist. Any variable can be emptied, by setting the value to null .
name = null;
null is not undefined ! null means: it defined, but the value of it is "nothing".
4.11. Functions
A Goat function is a block of code designed to perform a particular task. A Goat function is executed when "something" invokes it (calls it).
var myFunction = function(a, b) {
  return a * b; // the function returns the product of 'a' and 'b'
};
Why Functions? You can reuse code: Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.
4.11.1. Syntax
A Goat function is defined with the function keyword, followed by parentheses (). The parentheses may include parameter names separated by commas: (parameter_1, parameter_2, ...) . The code to be executed, by the function, is placed inside curly brackets: {} . To name a function (for the ability of invocation), the function object needs to be written to a variable:
var name = function(parameter_1, parameter_2, parameter_3) {
  //code to be executed
};
In the Goat language, the function keyword (it is long and is used very often ) can be changed to a dollar sign $ :
var name = $(parameter_1, parameter_2, parameter_3) {
  //code to be executed
};
Function parameters are listed inside the parentheses () in the function definition. Function arguments are the values received by the function when it is invoked. Inside the function, the arguments (the parameters) behave as local variables.
4.11.2. Return
When the Goat interpreter reaches a return statement , the function will stop executing, then the interpreter will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller":
var myFunction = function(a, b) {
  return a * b; // the function returns the product of 'a' and 'b'
};

var x = myFunction(4, 3);
The result in x will be 12 .
4.11.3. Invocation
The () operator invokes the function.
.
To invoke a function without arguments, use empty operator:
var doSomething = function() {
  //...
};

//...

doSomething();
To invoke a function with arguments, place arguments, separated by comma, inside the () operator:
var doSomething = function(a, b, c) {
  //...
};

//...

doSomething("test", 3.14, false);
An argument can be any expression - string, number, another function call etc.
4.11.4. Built-in functions
The Goat language has a lot of built-in functions (so-called built-in library). This library provides type definitions and functions for tasks such as string handling, mathematical computations, input/output processing and several other operating system services.
For example, the print function converts the first argument to a string and outputs it to a console:
print(2 + 3); // outputs: 5
Built-in functions are fully described in the appropriate chapter.
4.12. Objects
4.12.1. Real life objects, properties and methods
In real life, a car is an object . A car has properties like weight and color, and methods like start and stop.
Object:
var car = {};
Properties:
car.name = "Fiat";
car.model = 500;
car.weight = "850kg";
car.color = "white";
Methods:
car.start();
car.drive();
car.brake();
car.stop();
All cars have the same properties , but the property values differ from car to car.
All cars have the same methods , but the methods are performed at different times.
4.12.2. Goat objects
Recall that Goat variables are containers for data values. This code assigns a simple value ("Fiat") to a variable named car :
var car = "Fiat";
Objects are variables too. But objects can contain many values. This code assigns many values ("Fiat", 500, "white") to a variable named car:
var car = {type: "Fiat", model: 500, color:"white"};
The values are written as name:value pairs (name and value separated by a colon).
4.12.3. Properties
The name:values pairs (in Goat objects) are called properties.
var goat = { name: "Stinky", wool: Color.WHITE, age: 3 };
Property Value
name "Stinky"
wool Color.WHITE
age 3
4.12.4. Methods
Methods are actions that can be performed on objects. Methods are stored in properties as function definitions. In other words, methods are functions that are performed on an object.
var person = {
  firstName : "Scott",
  lastName : "Cameron",
  age : 45,
  
  fullName : function() {
    return firstName + ' ' + lastName;
  }
};

var name = person.fullName(); // result is: "Scott Cameron"
4.12.5. Definition
You define (and create) a Goat object with an object literal:
var person = { firstName : "Scott", lastName : "Cameron", age : 45 };
Spaces and line breaks are not important. An object definition can span multiple lines:
var person = {
  firstName : "Scott",
  lastName : "Cameron",
  age : 45
};
4.12.6. Accessing object properties
You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]
For example,
person.lastName
or
person["lastName"];
4.12.7. Accessing object methods
You access an object method with the following syntax:
objectName.methodName()
For example,
name = person.fullName();
4.12.8. Nested objects
Properties can be not only strings and numbers, but also arrays and objects:
var person = {
  firstName : "Scott",
  lastName : "Cameron",
  age : 45,
  children: [
    { firstName: "Ann", lastName: "Cameron", age: 10 },
    { firstName: "Dave", lastName: "Cameron", age: 14 }
  ]
};
Thus, objects can be unlimitedly nested within each other.
4.12.9. Objects, variables and references
Let's create a new object and assign it to a variable:
var a = { name: "Ivan", age: 33 };
Then, let's assign this variable to another variable:
var b = a;
Okay. Now, we try to look what the second variable contains:
print(b); // output: {name:"Ivan",age:33}
Right, it contains the same that contains the first variable. Now, we change one property of the second variable:
b.name = "John";
Now let's look at the result:
print(b); // output: {name:"John",age:33}
And now let's see what the first variable contains:
print(a); // output: {name:"John",age:33}
Thus, we changed the property of the second variable, but the first one also changed. Why? The Goat programming language does not store whole objects in variables. The Goat programming language stores in the variables only references to objects, but not the objects themselves. If you copy one variable to another, only the reference is copied.
What can you do if you need to make a real copy of the object? Use special method clone :
var a = { name: "Ivan", age: 33 };
var b = a.clone();
b.name = "Jonh";
print(b); // output: {name:"John",age:33}
print(a); // output: {name:"Ivan",age:33}
4.13. Scope
Scope determines the accessibility (visibility) of variables.
Variables declared within a Goat block (function, etc), become local to this block. Local variables have local scope: they can only be accessed within the block.
// code here can not use 'nickname'

var myFunction = function() {
  var nickname = "Stinky";
  
  // code here can use 'nickname'
};

// code here can not use 'nickname'
However, local variables can be accessed from inner blocks:
var myFunction = function() {
  var nickname = "Stinky";
  
  //...
  if (expression) {
    // code here can use 'nickname'
  }
  
  // code here can use 'nickname'
};
Functions are inner blocks also. So, each function can access variables, declared outside this function:
var myFunction = function() {
  var nickname = "Stinky";
  
  //...
  var innerFunction = function() {
    // code here can use 'nickname'
  };
  
  // code here can use 'nickname'
};
Variables declared within a block, redefines variables with the same names, declared outside a block. New variable uses only in this block:
var myFunction = function() {
  var nickname = "Stinky";
  //...
  print(nickname); // output: "Stinky"
  //...
  var innerFunction = function() {
    var nickname = "Dirty"; // redefine 'nickname' variable
    //...
    print(nickname); // output: "Dirty"
  };
  //...
  innerFunction();
  //...
  print(nickname); // output: "Stinky"
};
4.14. Strings
Goat strings are used for storing and manipulating text.
4.14.1. Definition
A Goat string is zero or more characters written inside double quotes.
var s = "Have a nice day";
4.14.2. Special characters
Because strings must be written within quotes, Goat will misunderstand this string:
var s = "The line "No, I am your father" is often misquoted as "Luke, I am your father."";
The string will be chopped to "The line " .
The solution to avoid this problem, is to use the backslash escape character. The backslash ( \ ) escape character turns special characters into string characters:
Code Result Description
\n New line
\r Carriage return
\t Tabulation
\" " Double quote
\\ \ Backslash
The sequence \" inserts a double quote in a string:
var s = "The line \"No, I am your father\" is often misquoted as \"Luke, I am your father.\"";
The sequence \\ inserts a backslash in a string:
var s = "The character \\ is called backslash.";
4.14.3. Strings are objects
The Goat language has no primitive types. All data represented as objects, including strings. For example, another way to define string is the explicit definition (as an object) by operator new :
var s = new String("My name is Ivan");
Don't create strings using operator new. This makes no sense. This example is needed to show that in principle, the string does not differ from other objects (it has a prototype, it can be created by the new operator, and so on).
Since a string is an object, it has properties, including methods. For example, the length method returns the length of a string:
var s = "Test";
var n = s.length(); // value of 'n' will be 4
4.14.4. String methods
length ( )
Returns the length of a string.
subString ( start, count )
Extracts a part of a string and returns the extracted part in a new string.
Parameters:
  • start (Integer): the starting index (position). 0 is the first symbol
  • count (Integer): optional; count of characters. If not specified, the substring begins with the character at the specified index and extends to the end of this string. If specified, anyway, the method returns not more symbols than it possible
Example:
var a = "This is an example.";
var b = a.subString(5, 2); // "is"
var c = a.subString(11); // "example."
split ( separator )
Splits a string into an array of substrings using a separator.
Parameter:
  • separator (Char): a separator
Example:
var s = "My name is James Bond";
var a = s.split(' '); // ["My","name","is","James","Bond"]
valueOf ( object )
Converts any object to a string.
Parameter:
  • object (any type): an object
Example:
var i = 256 * 256;
var s = String.valueOf(i); // "65536"
This is the static method, i.e. meant to be relevant to all the instances of a class rather than to any specific instance.
4.14.5. String operators
Remind that each object (include strings) supports these operators: -> (inherit), == (equal), != (not equal) and ! (logical not). Other operators are:
+, +=
Converts the second operand to a string and then concatenates strings.
Example:
var s0 = "hello" + ", " + "world!"; // "hello, world!";
var s1 = "test" + 123; // "test123"
var s2 = "value";
s2 += 3.14; // "value3.14"
One of the simplest methods to convert anything to a string is adding this object to an empty string:
var s = "" + 3.14; // "3.14"
<, <=, >, >=
Lexicographical comparison of strings. If the second operator is not a string, returns false .
Example:
print("hello" &gt;= "hell"); // outputs: true
4.15. Characters
A character ( Char ) is a type that corresponds to a symbol or grapheme: letter, digit etc.
4.15.1. Definition
A Goat char is one character written inside single quotes.
var c = 'A';
4.15.2. Special characters
As in strings, special characters after a backslash can be used here:
Code Result Description
\n New line
\r Carriage return
\t Tabulation
\' ' Single quote
\\ \ Backslash
The sequence \' means a single quote:
var c = '\'';
4.15.3. Char methods
valueOf ( object )
Static method. Converts object to a char.
Parameter:
  • object (any type): an object
Example:
var i = 65;
var c = Char.valueOf(i); // 'A'
If the object is an integer, returns a Char containing the character associated with the specified character code. Else, if the object is a char, just returns this object. Else, if the object is not an integer and is not a char, returns \0 (char with zero value).
4.15.4. Char operators
++, --
Increments or decrements of a Char variable (or a field) by 1.
Example:
var c = 'A'; // 'A';
c++; // 'B'
c++; // 'C'
c--; // 'B'
<, <=, >, >=
Comparison of two Char objects. If the second parameter is not a char, throws an IllegalArgument exception.
Example:
print('A' > 'B'); // outputs: false
What is an exception is described in the appropriate section.
4.16. Numbers
The Goat interpreter operates two type of numbers: integers and real numbers.
4.16.1. Integers
4.16.1.1. Definition
Integer numbers are written without decimal point:
var i = 3;
Also, Goat interprets numerical constants as hexadecimal if they are preceded by 0x :
var i = 0xFF;
and interprets numerical constants as binary if they are preceded by 0b :
var i = 0b1011;
4.16.1.2. Methods
toString ( radix )
Converts an integer to a string.
Parameter:
  • radix (Integer): optional, radix, can be 2, 10 or 16
Example:
var i = 254;
var s = i.toString(); // "254"
var h = "0x" + i.toString(16); // "0xFE"
4.16.1.3. Operators
The Integer type has more operators than the other types.
+, +=, -, -=, *, *=, /, /=
Addition, subtraction, multiplication and division. Note that multiplication and division have a higher precedence than addition and subtraction, just as in algebra. If the second operand is a real number, then the result will also be a real number. If the second operand is an integer, the result will integer. Else if the second operand is not a number, throws an IllegalArgument exception.
Example:
var a = 2;
var b = 3;
var c = 5;
var x = a + b * c; // 17
%, %=
Modulo (remainder). Returns the remainder of an integer divided by an integer.
Example:
var x = 17 % 10 // 7
<, <=, >, >=
Comparison of two numbers (integer or real number). If the second parameter is not a number, throws an IllegalArgument exception.
Example:
print(4 > 3); // outputs: false
++, --
Increments or decrements of an Integer variable (or a field) by 1.
Example:
var x = 1; // 1;
x++; // 2
x++; // 3
x--; // 2
~
The bitwise not , or complement, is a unary operation that performs logical negation on each bit, forming the ones complement of the given binary value. Bits that are 0 become 1, and those that are 1 become 0:
Example:
var x = 0b1011;
var n = ~x; // ...1110100
The integer consists of a large number of bits ( depending on the implementation, usually 64 ), all these bits change their values. So in this example, all first bits became 1.
<<, <<=
Left shift, i.e. bitwise operation that shifts all the bits of its operand. Shifts left by pushing zeros in from the right and let the leftmost bits fall off.
Example:
var x = 0b1011;
var s = x << 2; // 101100
Left shifts can be useful as an efficient way to perform multiplication of unsigned integers by powers of 2. Shifting left by n bits on unsigned binary number has the effect of multiplying it by 2 to the power of n :
var x = 5;
var s = x << 3; // 5 * 8 = 40
>>, >>=
Signed right shift, shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off.
Example:
var x = -5 // ...111011;
var s = x > 1; // ...111101 (-3)
>>>, >>>=
Unsigned (zero fill) right shift, one or more zero bits are pushed in from the left, and the rightmost bits fall off.
Example:
var x = 5 // 101;
var s = x >>> 1; // 010 (2)
&, &=
Bitwise and returns 1 only if both bits are 1.
Example:
var x = 5 // 101;
var y = 1 // 001;
var b = x & y; // 001 (1)
|, |=
Bitwise or returns 1 if one of the bits are 1.
Example:
var x = 5 // 101;
var y = 1 // 001;
var b = x | y; // 101 (5)
^, ^=
Bitwise xor (exclusive or ) returns 1 if the bits are different.
Example:
var x = 5 // 101;
var y = 1 // 001;
var b = x ^ y; // 100 (4)
4.16.2. Real numbers
4.16.2.1. Definition
Real numbers are written with the decimal point (dot):
var i = 3.14;
4.16.2.2. Operators
Real type supports only these operators: + , += , - , -= , * , *= , / , /= , < , <= , > , >= , ++ , -- . Bitwise operators are not supported.
4.17. Arrays
Goat arrays are used to store multiple values in a single variable.
4.17.1. Creating an array
Using an array literal [ ] :
var array_name = [item1, item2, ...];
For example:
var herd = ["Dirty", "Stinky", "Crazy"];
Spaces and line breaks are not important. A declaration can span multiple lines:
var herd = [
  "Dirty",
  "Stinky",
  "Crazy"
];
Array elements can be objects, arrays, numbers, strings... (remind that numbers, strings etc - all are objects). Arrays are special kinds of objects. You can have functions in an array. You can have even arrays in an array.
4.17.2. Access the elements of an array
You refer to an array element by referring to the index number. [0] is the first element in an array. [1] is the second. Array indexes start with 0.
This statement accesses the value of the first element in herd array:
var name = herd[0];
This statement modifies the first element in herd array:
herd[0] = "Nasty";
4.17.3. Adding array elements
The way to add a new element to an array is using the push method:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element ("Lemon") to fruits
4.17.4. The difference between arrays and objects
Arrays use numbered indexes.
Objects use named indexes.
Arrays are a special kind of objects, with numbered indexes.
4.17.5. Array methods
length ( )
Returns the length (count of items) of an array.
push ( object )
Adds a new item to the end of an array.
Parameter:
  • object (any type): an item
4.17.6. Looping array elements
The best way to loop through an array, is using a for loop:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var i, l = fruits.length();
for (i = 0; i < l; i++) {
  print(fruits[i] + "\n");
}
4.18. Booleans
A Goat Boolean represents one of two values: true or false .
4.18.1. Boolean values
Very often, in programming, you will need a data type that can only have one of two values, like
  • Yes or No
  • On or Off
  • True or False
For this, The Goat programming language has a Boolean data type. It can only take the values true or false .
var t = true;
var f = false;
4.18.2. Comparisons and conditions
The chapter "Comparisons" gives a full overview of comparison operators.
The chapter "Conditions" gives a full overview of conditional statements.
Here are some examples:
Operator Description Example
== Equal to if (day == "Monday")
> Greater than if (salary > 9000)
< Less than if (age < 18)
The Boolean value of an expression is the basis for all Goat comparisons and conditions.
4.19. Comparison and logical operators
Comparison and logical operators are used to test for true or false .
4.19.1. Comparison operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x = 5 , the table below explains the comparison operators:
Operator Description Comparing Returns
== Equal to x == 8 false
x == 5 true
x == "5" false
!= Not equal x != 8 true
> Greater than x > 8 false
< Less than x < 8 true
>= Greater than or equal to x >= 8 false
<= Less than or equal to x <= 5 true
Comparison operators can be used in conditional statements to compare values and take action depending on the result:
if (age < 18) print("Too young");
4.19.2. Logical operators
Logical operators are used to determine the logic between variables or values.
Given that x = 6 and y = 3 , the table below explains the logical operators:
Operator Description Example Returns
&& Logical and (x < 10 && y > 1) true
|| Logical or (x == 5 || y == 5) false
! Logical not !(x == y) true
Logical and (&&)
The expression A && B is true if A and B are both true ; else it is false .
Logical or (||)
The expression A || B is true if A or B (or both) are true ; if both are false , the expression is false .
Logical not (!)
The expression !A is true if A is false .
4.19.3. Conditional (ternary) operator
Goat also contains a conditional operator that assigns a value to a variable based on some condition:
variablename = (condition) ? value1 : value2
For example,
var voteable = (age < 18) ? "Too young" : "Old enough";
If the variable age is a value below 18, the value of the variable voteable will be "Too young" , otherwise the value of voteable will be "Old enough" .
4.19.4. Comparing different types
Comparing data of different types may give unexpected results. As a rule, the operators == and != check that the types of the two variables match, otherwise will be returned false. For example, you can compare numbers but you can not compare a number and a string. If you need to compare, just explicit convert an operand to another type to match the second operand:
var s = "1024";
var i = 256 * 4;
if (String.valueOf(i) == s) {
  // do something
}
There is one exclusion. You can compare integer numbers and real numbers although they are different types. An integer operand will be converted to a real before comparison.
4.20. Conditions
4.20.1. Conditional statements
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In Goat we have the following conditional statements:
  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed
4.20.2. The 'if' statement
Use the if statement to specify a block of Goat code to be executed if a condition is true. Syntax:
if (condition) {
  block of code to be executed if the condition is true
}
Example (outputs "Good day" ):
var hour = 12;
//...
if (hour < 18) {
  print("Good day");
}
Note that if is in lowercase letters. Uppercase letters ( If or IF ) will generate a Goat error.
4.20.3. The 'else' statement
Use the else statement to specify a block of code to be executed if the condition is false. Syntax:
if (condition) {
  block of code to be executed if the condition is true
}
else {
  block of code to be executed if the condition is false
}
Example (outputs "Good evening" ):
var hour = 12;
//...
if (hour < 18) {
  print("Good day");
}
else {
  print("Good evening");
}
4.20.4. The 'else if' statement
Use the else if statement to specify a new condition if the first condition is false. Syntax:
if (condition1) {
  block of code to be executed if condition1 is true
}
else if (condition2) {
  block of code to be executed if the condition1 is false and condition2 is true
}
else {
  block of code to be executed if the condition1 is false and condition2 is false
}
Example:
if (hour < 10) {
  print("Good morning");
}
else if (hour < 18) {
  print("Good day");
}
else {
  print("Good evening");
}
4.21. Switch statement
The switch statement is used to perform different actions based on different conditions. Use the switch statement to select one of many blocks of code to be executed.
4.21.1. Syntax
switch(expression) {
  case n:
    code block
    break;
  case n:
    code block
    break;
  default:
    code block
}
This is how it works:
  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
Example. This function converts weekday (as a number between 0 and 6) to a string:
var weekday = function(number) {
  var day;
  switch (number) {
    case 0:
      day = "Sunday";
      break;
    case 1:
      day = "Monday";
      break;
    case 2:
      day = "Tuesday";
      break;
    case 3:
      day = "Wednesday";
      break;
    case 4:
      day = "Thursday";
      break;
    case 5:
      day = "Friday";
      break;
    case 6:
      day = "Saturday";
  }
  return day;
};
4.21.2. The 'break' keyword
When Goat reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break. There is no need for more testing.
It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
4.21.3. The 'default' keyword
The default keyword specifies the code to run if there is no case match.
Example. This function converts weekday (as a number between 0 and 6) to a string, but if weekday is neither Saturday (6) nor Sunday (0), returns a default message:
var weekday = function(number) {
  var day;
  switch (number) {
    case 0:
      day = "Sunday";
      break;
    case 6:
      day = "Saturday";
      break;
    default:
      day = "Working day";
  }
  return day;
};
The default case (if exists) should be the last case in a switch block.
4.21.4. Common code blocks
Sometimes you will want different switch cases to use the same code:
var weekday = function(number) {
  var day;
  switch (number) {
    case 0:
      day = "Sunday";
      break;
    case 6:
      day = "Saturday";
      break;
    case 4:
    case 5:
      day = "Soon it is Weekend";
      break;
    default:
      day = "Working day";
  }
  return day;
};
4.22. Loops
4.22.1. What is loops
Loops can execute a block of code a number of times.
Loops are handy, if you want to run the same code over and over again, each time with a different value. Often this is the case when working with arrays.
For example, we have an array:
var herd = ["Dirty", "Stinky", "Crazy", "Nasty", "Dumb", "Dumber"];
Instead of writing:
print(herd[0] + "\n");
print(herd[1] + "\n");
print(herd[2] + "\n");
print(herd[3] + "\n");
print(herd[4] + "\n");
print(herd[5] + "\n");
You can write:
var i, l = herd.length();
for (i = 0; i < l; i++) {
  print(herd[i] + "\n");
}
4.22.2. Different kinds of loops
Goat supports different kinds of loops:
  • for - loops through a block of code a number of times;
  • for..in - loops through the properties of an object;
  • while - loops through a block of code while a specified condition is true;
  • do..while - also loops through a block of code while a specified condition is true.
4.22.3. The 'for' loop
The for loop is often the tool you will use when you want to create a loop. The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
  code block to be executed
}
Statement 1 is executed before the loop (the code block) starts.
Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
Example (outputs "0123456789" ):
var i;
for (i = 0; i < 10; i++) {
  print(i);
}
From the example above, you can read:
Statement 1 sets a variable before the loop starts ( i = 0 ).
Statement 2 defines the condition for the loop to run ( i must be less than 10).
Statement 3 increases a value ( i++ ) each time the code block in the loop has been executed.
4.22.3.1. Statement 1
Normally you will use statement 1 to initialize the variable used in the loop ( i = 0 ). This is not always the case, Goat doesn't care. Statement 1 is optional. You can omit statement 1 (like when your values are set before the loop starts):
var i = 0;
for (; i < 10; i++) {
  print(i);
}
Also, you can declare a variable in statement 1 using var keyword:
for (var i = 0; i < 10; i++) {
  print(i);
}
This variable will be visible only inside the 'for' loop.
4.22.3.2. Statement 2
Often statement 2 is used to evaluate the condition of the initial variable. This is not always the case, Goat doesn't care. Statement 2 is also optional. If statement 2 returns true , the loop will start over again, if it returns false , the loop will end.
If you omit statement 2, you must provide a break or a return inside the loop. Otherwise the loop will never end.
4.22.3.3. Statement 3
Often statement 3 increments the value of the initial variable. This is not always the case, Goat doesn't care, and statement 3 is optional. Statement 3 can do anything like negative increment ( i-- ), positive increment ( i = i + 15 ), or anything else. Statement 3 can also be omitted (like when you increment your values inside the loop):
for (i = 0; i < 10; ) {
  print(i);
  i++;
}
4.22.4. The 'for..in' loop
The Goat for..in statement loops through the properties of an object:
var person = {name: "Ivan", age: 33, gender: "male"};
var x;
for (x in person) {
  print(x + ": " + person[x] + "\n");
}
Output:
name: Ivan
age: 33
genger: male
Note that objects store unordered pairs key:value . The order of traversal of object properties may not match with the order of the properties at object creation. In the example above, the output can be:
age: 33
name: Ivan
genger: male
4.22.5. The 'while' loop
The while loop loops through a block of code as long as a specified condition is true . Syntax:
while (condition) {
  code block to be executed
}
Example (outputs "0123456789" ):
var i = 0;
while (i < 10) {
  print(i);
  i++;
}
Note: if you forget to increase the variable used in the condition, the loop will never end.
4.22.6. The 'do..while' loop
The do..while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true , then it will repeat the loop as long as the condition is true . Syntax:
do {
  code block to be executed
}
while (condition);
Example. The loop will always be executed at least once, even if the condition is false , because the code block is executed before the condition is tested:
var i = 0;
do {
  print(i);
  i++;
} while (i < 10);
4.22.7. The 'break' statement
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement. The break statement can also be used to "jump out" of a loop. The break statement breaks the loop and continues executing the code after the loop (if any):
var i;
for (i = 0; i < 10; i++) {
  if (i == 6)
    break;
  print(i);
}
Output: 012345 .
4.22.8. The 'continue' statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 3:
var i;
for (i = 0; i < 10; i++) {
  if (i == 3)
    continue;
  print(i);
}
Output: 012456789 .
4.23. Exceptions
4.23.1. Errors will happen!
When executing Goat code, different errors can occur. For example, division by zero:
print(1 / 0); // oops
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the result.
4.23.2. Try and catch
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The Goat statements try and catch come in pairs:
try {
  Block of code to try
}
catch(err) {
  Block of code to handle errors
}
Example:
try {
  print(4 / 4);
  print(4 / 2);
  print(4 / 1);
  print(4 / 0);
}
catch(err) {
  print("Error");
}
Output:
124Error
When an error occurs, Goat will normally stop and generate an error object. The technical term for this is: Goat will throw an exception (throw an error).
4.23.3. The 'throw' statement
The throw statement allows you to create a custom error.
Technically you can (throw an error). The exception can be any object:
throw "Oops!"; // throw a string
The thrown object passes as parameter of the catch statement.
If you use throw together with try and catch , you can control program flow and generate custom error messages.
var kelvin2Celsius = function(value) {
  if (value < 0)
    throw "Wrong parameter: " + value;
  
  return value -273.15;
};

try {
  print("\n" + kelvin2Celsius(300));
  print("\n" + kelvin2Celsius(0));
  print("\n" + kelvin2Celsius(-10));
}
catch(err) {
  print("\n" + err);
}
Output:
26.85
-273.15
Wrong parameter: -10
4.23.4. The 'finally' statement
The finally statement lets you execute code, after try and catch, regardless of the result:
try {
  Block of code to try
}
catch(err) {
  Block of code to handle errors
}
finally {
  Block of code to be executed regardless of the try / catch result
}
4.23.5. The error object
The exception can be any object. For some situations, the interpreter throws predefined exception objects, such as:
Exception Situation
NameIsNotDefined Attempt to call a function with an undefined name. For example, Print (first capital letter) instead of print
IsNotAFunction Attempt to call a function: name is defined, but it is not a function. var f = 0; f();
OperatorIsNotDefined Attempt to use an operator that is not applicable to this data type. For example, you can not multiply strings: "hello" * "world"
DivisionByZero Division by zero, print(1 / 0);
IncorrectIndex Index of an array is not an integer, var a = [0, 13, 666]; print(a["0"]);
OutOfBounds Index of an array is too big , var a = [0, 13, 666]; print(a[10]);
IllegalArgument Wrong argument of a function or an operator
Each object (include error objects) has the instanceOf method. You can use this method to determine the type of exception:
try {
  // do something
}
catch(err) {
  if (err.instanceOf(Exception.OutOfBounds)) {
    // do domething if out of bounds
  }
}
4.24. Import
4.24.1. Overview
Sometimes the program becomes so large that it is more reasonable to separate it into several files. In addition, you can use pre-designed libraries - say, to recognize XML files. Goat provides a way to include files to a program using an import keyword.
import "xml.goat";

// now, you can use functions from XML library:
var root = XML.parse("<root></root>");
No file will be imported twice. For example, your program uses library A and library B . But library B uses (imports) library A also. So, library A will be imported only once, for all project.
Where the interpreter finds files to import?
  • first, in the current folder, where was started Goat script;
  • second, in the list of folders specified in the --lib option of the interpreter.
4.24.2. --lib option
Path (paths) to importable files. For example, folder c:\goat\lib contains Goat standard library; so, to use it, launch the interpreter with --lib option:
goat.exe program.goat --lib=c:\goat\lib
Several paths can be separated by a semicolon. The interpreter for each imported file first searches the first path in the list, then the second one, and so on.
4.25. Debugging
4.25.1. Interactive mode
Goat has two basic modes: script and interactive. The normal mode is the mode where the scripted and finished files are run in the Goat interpreter. Interactive mode is a command line shell which gives immediate feedback for each statement while running previously fed statements in active memory. As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole.
To start interactive mode, launch the Goat interpreter without script file (in common cases without any parameters):
goat.exe
Will open a console:
?
Enter any correct statement and press Enter:
? var i = 0;

?
In the example above, the interpreter will create a variable i and wait for the new statement to be entered. So, now you can print the value of the variable:
? print(i);
0
?
You can use any statements you want:
? for (var k = 0; k < 10; k++) print(k);
0123456789
?
If statement takes more than one line, add a backslash to go a new line:
? for (var k = 0; k < 10; k++) { \
  if (k == 3) continue; \
  print(k); \
}
012456789
?
The values of all variables are saved:
? var obj = {};

? obj.field = 1;

? print(obj);
{field:1};
?
The special statement exit exits interactive mode.
exit
4.25.2. Step-by-step debugging
4.25.2.1. The 'debug' keyword
The debug keyword stops the execution of Goat, and switch the interpreter to step-by-step mode. If no debugging is available, the debug statement has no effect.
var i, j;
for (i = 0; i < 10; i++) {
  debug;
  j = i * i;
  print("" + j + "\n");
}
Then launch the interpreter with --debug option:
goat.exe program.goat --debug
The program will start and then stop on debug keyword:
> program.goat, 3.7: debug;
[step] ?
4.25.2.2. Step-by-step dialog
After stop (and each step) the interpreter outputs step-by-step dialog and wait for a command:
> program.goat, 4.9: j = i * i;
[step] ?
In the example above, the individual elements of the dialog have the following meanings:
Element Description
program.goat Filename of the current script
4.9 Current line (4) and symbol in line (9)
j = i * i; The expression that will now be executed
[step] Command by default
? Prompt to enter a command
You can enter the following commands:
Short command Full command Description
c continue Continue until the next stop on debug statement.
s step Next step (over). If this step is a function call, then the function is executed entirely.
i into Next step (into). If the next step is a function call, the interpreter "enters inside" the function and then stops at the first statement of the function.
o out Next step (out). The interpreter executes the current function to the end and stops at the first statement after calling this function.
$var_name Prints the contents of a variable var_name .
If you press Enter without entering any command, the default command (in square brackets) will be executed. Typically, the default command is the last command executed.
5. Advanced programming
Forget everything you learned in school.
5.1. The new look at objects
5.1.1. Keys and values
Objects are containers for pairs key:value :
var person = { firstName : "Scott", lastName : "Cameron", age : 45 };
The key:value pairs (in Goat objects) are called properties.
Values can be any objects: strings, numbers etc. What about keys? In the example above, keys are identifiers (such as names of variables).In common cases, using identifiers as keys is enough: it is convenient. You always can to add a new property using the dot operator . :
person.profession = "Programmer";
But, keys can be not only identifiers. You can use any object as a key. For example, integers:
person[3] = "value";
...or booleans:
person[true] = false;
...and, of course, strings:
person["profession"] = "Programmer";
If you use a string as a key, and this string can be an identifier (the first character must be a letter or an underscore ( _ ), subsequent characters may be letters, digits or underscores), Goat transforms this string to an identifier. Later you can access to this field using identifier:
person["weight"] = 80;
//...
print(person.weight); // output: 80
And vice versa, any property declared using an identifier, can be accessed using a string:
person.weight = 80;
//...
print(person["weight"]); // output: 80
So, objects are containers for pairs key:value , where the key can be an identifier or any object, and the value can be any object. However, the Goat program works a little faster if you use identifiers as keys, so this is the preferred method.
5.1.2. Each object has some predefined methods
Goat adds these methods to each object.
instanceOf ( object )
Returns whether an object is derived from another object or not.
Parameter:
  • object (any type): the prototype
Example:
var isInteger = $(obj) {
  return obj.instanceOf(Integer);
};
The method is used to determine the type (more correctly, the prototype) of the object. What is a prototype, will be described a little later.
clone ( )
Returns a clone of the object, that is, a new object in which all properties are the same as in the source object.
Example:
var a = { name: "Ivan", age: 33 };
var b = a.clone();
b.name = "Jonh";
print(b); // output: {name:"John",age:33}
print(a); // output: {name:"Ivan",age:33}
This is required if you need to get a real copy of the object, then change it and leave the original object unchanged.
flat ( )
Returns a flat object, that is, an object that contains all the properties of the source object, as well as all properties of all prototypes of the source object. What is a prototype, will be described a little later.
5.1.3. Everything is an object
All data (strings, numbers, booleans) represented as objects. These are "special" objects that have special behavior. But beyond this, these objects do everything the same as other, "ordinary" objects.
For example, you can add a property for a string:
var str = "hello!";
str.somePropertyName = 123;
...or add some method to an integer:
var n = 123;
n.increment = $(){
  return this + 1;
};
As each object has some predefined methods, strings, booleans, integers, and others also have all these methods:
var str = "hello!";
print(str.instanceOf(String)); // output: true

var num = 10;
print(num.instanceOf(Boolean)); // ounput: false
5.2. Methods
5.2.1. Difference between method and function
A method in object-oriented programming is a function associated with an object.
In other words, functions work only with parameters, but methods also "see" all the properties (fields and other methods) of own object and can modify these.
Example. Declare an object obj that contains one field x and one method getX . The method can access the field:
var obj = {
  x: 10;
  
  getX : $() {
    return x;
  }
};

var n = obj.getX(); // 10
5.2.2. Search order
Since a property (or variable) with the same name can be defined in many places, the programming language specifies a clear order of searching for the value by name.
Suppose we want to read a variable named x . The highest priority has local variables:
var obj = {
  x: 10; // property 'x'
  
  getX : $() {
    var x = 2 + 3; // local variable 'x'
    return x;
  }
};

var n = obj.getX(); // 5
If a local variable with this name is not found, the Goat programming language tries to find this name in the list of arguments of the method:
var obj = {
  x: 10; // property 'x'
  
  getX : $(x) { // method with argument named 'x'
    return x;
  }
};

var n = obj.getX(7); // 7
Then the search is performed in the object properties:
var x = 777; // external variable 'x'

var obj = {
  x: 10; // property 'x'
  
  getX : $() {
    return x;
  }
};

var n = obj.getX(); // 10
The last thing to do is look for variables outside the object:
var x = 777; // external variable 'x'

var obj = {
  getX : $() {
    return x;
  }
};

var n = obj.getX(); // 777
5.2.3. The 'this' keyword
When a method is called, a special variable named this is always defined. This variable refers to the object whose method was called. You can not overwrite the value of this variable. This variable is used to explicitly access the properties of the "own" object.
var obj = {
  x: 10; // property 'x'
  
  getX : $() {
    return this.x;
  }
};

var n = obj.getX(); // 10
In fact, the example above is completely analogous to this example:
var obj = {
  x: 10; // property 'x'
  
  getX : $() {
    return x; // without 'this' keyword
  }
};

var n = obj.getX(); // 10
That is, in most cases, we can do without using this keyword. But in some cases, this keyword cannot be avoided. For example, if you already have a local variable or an argument with that name, but you want to explicit read or write the property of the object:
var obj = {
  x: 10; // property 'x'
  
  getX : $() {
    return x;
  }
  
  setX " $(x) {
    this.x = x; // read the argument 'x' and write the property 'x'
  }
};

obj.setX(777);
var n = obj.getX(); // 777
Or, you can add new properties to own object (which are not yet there):
var obj = {
  x: 10; // property 'x'
  
  init : $() { // constructor
    this.y = 20; // add a new property 'y'
  }
};
5.3. Prototypes
5.3.1. Prototype and inheritance
Goat is prototype-oriented language. What is "prototype" means?
A prototype is an object from which other objects inherit properties and methods. Any object can be a prototype for another object.
Inheritance is when an object is based on another object using the same implementation.
How does it work? When accessing an object (method call or field reading), the Goat programming language first looks for this property in the object itself. If Goat does not find it, tries to look for this property in the prototype object. If still not found, then Goat is searching in a prototype of the prototype, and so on.
// declare an object:
var parent = { x: 1 };

// inherit another object:
var child = parent -> { y: 2, z: 3 };

// now you have access to properties in the parent object:
print(child.x); // output: 1
5.3.2. Operator ->
Operator -> builds a new object from the prototype and description:
var obj = prototype -> description;
A prototype is any object from which properties (fields and methods) will be used if properties with such names are not found in the child object.
A description is an object that will be cloned before a prototype is attached to it. The description thus extends the prototype, and as a result, a new object is created that contains both its own properties and the properties of all its parents.
Example:
// declare an object:
var A = { x: 1 };

// inherit:
var B = A -> { y: 2, z: 3 }; // 'B' contains 'x', 'y' and 'z'
Of course, you can declare a description elsewhere:
// declare an object:
var A = { x: 1 };

// declare a description:
var D = { y: 2, z: 3 };

// inherit:
var B = A -> D; // 'B' still contains 'x', 'y' and 'z'
5.3.3. Prototype сhain
If you created a new object using an operator -> , then this object, in turn, can also be a prototype of some other object:
// declare an object:
var A = { x: 1 };

// inherit first time:
var B = A -> { y: 2 }; // 'B' contains 'x' and 'y'

// inherit second time:
var C = B -> { z: 3 }; // 'C' contains 'x', 'y' and 'z'
The Goat programming language looks for the property by its name along the whole prototype chain, from last to first prototype. For example,
print(C.x);
The order of search is:
  • first, a property named x will be searched in the C object and will not be found;
  • second, a property will be searched in the B object and will not be found;
  • finally, a property will be searched in the A object and will be found.
Another example, attempt to read an undefined property:
print(C.w);
In this case, the Goat programming language will scan the whole prototype chain (first C , then B , then A ), but will not find the properties and return undefined result.
5.3.4. Changing the prototype
You can not change the prototype of the object. Instead, you can change properties of the prototype itself. In this case, these properties will immediately change in all children:
// declare an object:
var A = { x: 1 };

// inherit:
var B = A -> { y: 2, z: 3 };

// read the value of 'x' property (of the child object):
print(B.x); // output: 1

// change the value of 'x' property (in the parent object):
A.x = 777;

// read the value of 'x' property again:
print(B.x); // output: 777
5.3.5. The 'new' operator
The new operator creates a new object from the prototype and then calls a special method - constructor to initialize the object.
// declare the class:
var Vector = {
  x : 0,
  y : 0
};

// create the object using the 'new' operator
var v = new Vector();
In the simplest case, as in the example above, this operation is completely analogous to the inheritance from the prototype:
var v = Vector -> { };
But, in addition to inheritance, the new operator calls a chain of constructors.
5.3.5.1. Constructor
A constructor is a method named init .
// declare the class:
var Vector = {
  init : $() {
    this.x = 0;
    this.y = 0;
  }
};

// create the object using the 'new' operator
var v = new Vector();
Output:
{x:0,y:0}
Note that in the first example (without the constructor), the x and y variables do not belong to the new object, but to the prototype. In the new example, the variables are created each time the object is created by the new operator, and these variables belong to the object.
Where can this be useful? This is necessary in cases where each object must have its own independent data set.
Let's consider another example. Say there is some "Dictionary" class that stores values in an associative array:
var Dictionary = {
  data : {},
  
  add : $(english, french) {
    data[english] = french;
  }
};

// create the first dictionary
var d1 = new Dictionary();
d1.add("red", "rouge");
d1.add("green", "vert");

// create the second dicrionary
var d2 = new Dictionary();
d2.add("blue", "bleu");
d2.add("black", "noir");

// read the data from the first dictionary:
print(d1.data);
Will this work? No. The output is:
{"red":"rouge","green":"vert","blue":"bleu","black":"noir"}
The resulting object contains data from both the first and second dictionary. Why? Because the d.data object does not belong to d1 object, but belongs to its prototype, that is, both objects d1 and d2 have access to it. But this is wrong. Each dictionary instance must have its own object for data storage. You can create this object in the constructor:
var Dictionary = {
  init : $() {
    this.data = {};
  },
  
  add : $(english, french) {
    data[english] = french;
  }
};

// create the first dictionary
var d1 = new Dictionary();
d1.add("red", "rouge");
d1.add("green", "vert");

// create the second dicrionary
var d2 = new Dictionary();
d2.add("blue", "bleu");
d2.add("black", "noir");

// read the data from the first dictionary:
print(d1.data);
Now it's right:
{"red":"rouge","green":"vert"}
So, constructors are needed to initialize objects, so that each instance of a class, created using the new operator, contains its unique data.
5.3.5.2. Constructor with parameters
An init method can have parameters that are passed to it as arguments of the new operator:
var Vector = {
  init : $(x, y) {
    this.x = x;
    this.y = y;
  }
};

var v = new Vector(10, 20);

print(v);

Output:
{x:10,y:20}
So, the parameterized constructor allows initializing an object using the data passed as parameters.
5.3.5.3. Constructors chain
Consider a chain of prototypes, with each prototype containing an init method:
var A = {
  init : $() {
    this.x = 1;
  }
};

var B = A -> {
  init : $() {
    this.y = 2;
  }
};

var C = B -> {
  init : $() {
    this.z = 3;
  }
};

var obj = new C();

print(obj);
Output:
{x:1,y:2,z:3}
As you can see, all three constructors were called, because the resulting object contains all three variables.
How it works. If the prototype chain contains prototypes that have an init method, then the new operator calls these methods one by one, starting from the "deepest" prototype.
In the example above, the init method of object A will be called first, then the init method of object B , then the init method of object C .
This order of calling constructors allows you to correctly initialize the object. Let's try to change the value of the variable in the last constructor:
var A = {
  init : $() {
    this.x = 1;
  }
};

var B = A -> {
  init : $() {
    this.y = 2;
  }
};

var C = B -> {
  init : $() {
    x = 7;
    this.z = 3;
  }
};

var a = new A();
var b = new B();
var c = new C();

print("" + a + "\n" + b + "\n" + c);

Output:
{x:1}
{x:1,y:2}
{x:7,y:2,z:3}
You see? Each subsequent constructor in the chain complements the object initialization. During this, of course, the results of the work of the previous constructor can be changed.
5.3.5.4. Passing parameters to the constructors chain
When passing parameters through the new operator, all parameters are passed only to the first constructor:
var A = {
  init : $() {
    this.x = 10;
  }
};

var B = A -> {
  init : $(y, z) {
    this.y = y;
    this.z = z;
  }
};

var obj = new B(20, 30);

print(obj);

Output:
{x:10,y:20,z:30}
All remaining constructors in the chain are called without parameters.
5.3.6. Overriding
You can override properties (fields and methods) in children objects.
Method overriding, in Goat programming language, is a language feature that allows a subobject to provide a specific implementation of a method that is already provided by one of its prototypes. The implementation in the subobject overrides (replaces) the implementation in the prototype by providing a method that has the same name as the method in the prototype. The version of a method that is executed will be determined by the object that is used to invoke it.
// the object with the method which will be overridden:
var Animal = {
  talk : $() {
    print("This animal can not speak.\n");
  }
};

// inherit the first object and override the method:
var Goat = Animal -> {
  talk : $() {
    print("Baa!\n");
  }
};

// inherit the second object and override the method again:
var Cow = Animal -> {
  talk : $() {
    print("Moo!\n");
  }
};

// inherit the third object but does not override the method:
var Fish = Animal -> {

};

// create three objects and call the methods:
var g = new Goat();
var c = new Cow();
var f = new Fish();

g.talk();
c.talk();
f.talk();
Output:
Baa!
Moo!
This animal can not speak.
The same rule for fields. Field with the same name as in prototype overrides the previous field:
// the object with the field which will be overridden:
var Programmer = {
  salary : 1000
};

// inherit the first object and override the field:
var Senior = Programmer -> {
  salary : 1500
};

// inherit the second object but does not override the field:
var UnitTester = Programmer -> {

};

// create two objects and read the fields:
var s = new Senior();
var ut = new UnitTester();

print(s.salary);
print("\n");
print(ut.salary);
Output:
1500
1000
5.3.7. Operator overloading
Operators can be redefined. From the point of view of the interpreter, the operator is no different from the usual method. The method that defines the operator has the same name as the operator itself. Let's consider an example:
var Vector = {
  init : $(x, y) {
    this.x = x; this.y = y
  },
  toString : $() {
    return "X: " + x + ", Y: " + y;
  },
  "+" : $(vec) {
    return new Vector(x + vec.x, y + vec.y);
  },
  "*" : $(val) {
    return new Vector(x * val, y * val);
  }
};

var v1 = new Vector(100, 200);
var v2 = new Vector(200, 400);

var v3 = v1 + v2;
print(v3.toString() + "\n");

var v4 = v1 * 5;
print(v4.toString() + "\n");

Output:
X: 300, Y: 600
X: 500, Y: 1000
In the example above, the class "Vector" is described. A vector is a complex data structure. Vectors can be added, a vector can be multiplied by a number. Therefore, for this structure, two operators are defined: + and * . Each operator returns a new vector as the result of an operation of addition or multiplication.
How it works. When the interpreter processes a binary operator, it finds the corresponding method at the left operand and calls this method, passing the right operand as the parameter. The result of the operation is the return value of the method. In the case of a unary operator, the method is called without parameters.
Unary operators: ++ , -- , ! , ~ , + , - , and binary operators + , - , * , / , % , << , >> , >>> , & , ^ , | , < , <= , > , >= , && , || can be overloaded.
Operators "Assign by" ( += , *= , etc.) can be overloaded also.
5.3.8. Multiple inheritance
Objects in the Goat programming language can have more than one prototype. In this case, the resulting object will contain all the properties and methods of all parents:
var Animal = {
  eat : $() {
    print("'eat' method is called\n");
  }
};

var Mammal = Animal -> {
  drinkMilk : $() {
    print("'drinkMilk' method is called\n");
  }
};

var WingedAnimal = Animal -> {
  flap : $() {
    print("'flap' method is called\n");
  }
};

// A bat is a winged mammal
var Bat = [Mammal, WingedAnimal] -> {

};

var bat = new Bat();
bat.flap();
bat.drinkMilk();
bat.eat();
Output:
'flap' method is called
'drinkMilk' method is called
'eat' method is called
There is one problem that is called the "diamond problem". Consider this structure of inheritance:
var A = {
  alpha : 1
};

var B = A -> {
  beta : 2
};

var C = A -> {
  beta : 3
};

var D = [B, C] -> {
  gamma : 4
};

var d = new D();

print(d.alpha);
print(d.beta);
print(d.gamma);
The D objects inherits from B and D . But both B and C objects have the beta property, in B object the property equals 2, in C object property equals 3. So, what is the value of the d.beta property? 2 or 3? The correct answer is 2.
The interpreter uses depth search. If he did not find a property in the object, it first explores the properties of the first (left) prototype, and then all the prototypes of this prototype ( D->B->A ). And only then the next chain of prototypes is explored ( D->C->A ).
Be careful with multiple inheritance. Sometimes this type of inheritance is very useful, but misuse can lead to errors.
5.3.9. The 'instanceOf' method
The method checks whether there is an object passed as an argument in the prototype chain. This is a way to determine if an object is instantiated from a specific prototype.
Each object has the instanceOf method.
Consider this code:
var A = { };
var B = A -> { };
var C = A -> { };

var X = new A();
var Y = new B();
var Z = new C();
So,
  • X.instanceOf(A) returns true because object A is a prototype of object X ;
  • but X.instanceOf(B) and X.instanceOf(C) returns false because objects B and C are not prototypes of object X ;
  • Y.instanceOf(B) returns true because object B is a prototype of object Y ;
  • Y.instanceOf(A) returns true because object A is a prototype of object B and object B is a prototype of object Y ;
  • Y.instanceOf(C) returns false because object C is not prototypes of object Y ;
  • Z.instanceOf(C) returns true because object C is a prototype of object Z ;
  • Z.instanceOf(A) returns true because object A is a prototype of object C and object C is a prototype of object Z ;
  • Z.instanceOf(B) returns false because object B is not prototype of object Z .
5.3.10. The 'clone' method
Returns a clone of the object, that is, a new object in which all properties are the same as in the source object.
Each object has the clone method.
The method creates a new object and then copies all the properties and methods from the original object to the new one. Now, if you change the copy, the original object will remain unchanged:
var original = {
  x : 10,
  y : 20,
  z : 30
};

var copy = original.clone();

copy.y = 100;

print(original);
print(copy);
Output:
{x:10,y:20,z:30}{x:10,y:100,z:30}
If possible, do not use clone method, inherit an object instead! Cloning is a very expensive operation, due to the need to copy each field.
The clone method is implicitly called in some other operations. For example, operators -> (inherit) and @ (lock, see below) call this method. This method (however, like all the others) can be redefined. And then the operators will call the overridden method.
For example, you can prevent cloning an object, and instead of a clone, return the object itself:
var original = {
  x : 10,
  y : 20,
  z : 30,
  
  clone : $() {
    return this;
  }
};

var copy = original.clone(); // copy is the same object as the original
5.3.11. The 'flat' method
Returns a flat object, that is, an object that contains all the properties of the source object, as well as all properties of all prototypes of the source object.
Each object has the flat method.
The method creates a new object and then copies all the properties and methods from the original object and from all prototypes of the original object. Thus, a new object has no prototypes but has all data from the original object:
var A = {
  x : 10
};

var B = A -> {
  y : 20
};

var C = B-> {
  z : 30
};

var F = C.flat();

print(F);
Output:
{x:10,y:20,z:30}
The new object is, as it were, "flat", the same as if it were declared thus:
var F = {
  x : 10,
  y : 20,
  z : 30
};
Note that the copying is done starting from the very "deep" prototype. Thus, if somewhere in the chain of prototypes some property was redefined, then the "flat" object will contain an overridden property:
var A = {
  x : 10
};

var B = A -> {
  x : 15, // overrided
  y : 20
};

var C = B-> {
  z : 30
};

var F = C.flat();

print(F);
Output:
{x:15,y:20,z:30}
5.3.12. Prototypes of built-in types
Each object of built-in type (string, integer etc) has own built-in prototype:
  • String is the prototype for strings. Every time you define a string, for example, var s = "hello, world" you create a new object that has the String prototype;
  • Integer is the prototype for integers;
  • Real is the prototype for floating-point numbers;
  • Char is the prototype for characters;
  • Boolean is the prototype for booleans;
  • Null is the prototype for null constant;
  • Array is the prototype for all arrays;
  • functions are also objects! Each time you declare a function, for example, var f=$(){ } an object is created, the prototype of which is Function .
Other prototypes of built-in classes are: Thread , Exception , File , StringBuilder , ByteArray .
Each prototype has, respectively, its properties, methods, and operators. For example, strings have a predefined + operator, which allows to concatenate strings.
Using a prototype, you can check whether the object is the right data type. Here is an example of a function, at the beginning of which it is checked whether the argument is an integer:
var f = $(value) {
  if (value.instanceOf(Integer)) {
    //...
  }
};
5.4. All about nothing
There are special objects in the Goat programming language that means "nothing": undefined , null and void .
5.4.1. undefined
As previously described, undefined means that no value has been assigned. Any variable defined using "var" keyword without an initial value has the value of undefined :
var v;
print(v); // output: "undefined"
Moreover, if you try to read the value of an undeclared variable, this value will also be undefined :
print(n3j9v0kXXq); // output: "undefined"
The same is true if you read a non-existent property of an object:
var obj = { x: 10, y: 20 };
print(obj.z); // output: "undefined"
Is undefined an object? Yes. This is an object, and it even has its own prototype: Undefined . But you can not do anything with this object. You cannot change properties of undefined , you can not call methods. All you can is compare this object to undefined :
if (obj == undedined) {
  //...
}
Or:
if (defined(obj)) {
  //...
}
5.4.2. null
The second special object. It means that the value was defined, that is, it is not equal to undefined , but it is empty. Null is not numeric, is not a string. This is "nothing".
Unlike undefined , the null object is not created implicitly anywhere. It can be explicitly assigned to a variable or returned from a method:
var n = null;

var f = $() {
  //...
  return null;
};
null is not equal to undefined :
var u; // undefined

if (u == null) { // false!
  //...
}

var n = null;

if (defined(n)) { // true!
  // ...
}

Is null an object? Yes. This is an object, like undefined , and it has its own prototype: Null . You can not add prototypes to null , but you can call methods, for example:
print(null.instanceOf(Null)); // "true"
5.4.3. void
The third data type, which combines the two previous ones.
The void object has prototype Void ", and both Undefined and Null inheriths from Void . So, in other words, undefined is void and null is void . This is used if you need to check with one operation whether the object is null or undefined :
var f = $(value) {
  if (value == void) {
    throw new Exception.IllegalArgument();
  }
  
  //...
};
This is the same as:
var f = $(value) {
  if (value == undefined || value == null) {
    throw new Exception.IllegalArgument();
  }
  
  //...
};
5.4.4. Operator ?. (void guard)
You can not read a property from undefined or null . If you try to read a property (or call a method) from undefined , this will throw an exception Exception.CanNotReadPropertyOfUndefined . If you try to read a property from null , then null contains no properties (except standard methods and operators). Thus, sometimes it is necessary to check whether a variable (most often an argument of a method) is a void. This avoids unintended consequences like exceptions. For example:
// safe 'exist' field reading from 'some.object.that.might.not.exist':
if (some != void) {
  if (some.object != void) {
    if (some.object.that != void) {
      if (some.object.that.might != void) {
        if (some.object.that.might.not != void) {
          return some.object.that.might.not.exist;
        }
      }
    }
  }
}
return 0;
This, probably, is not the shortest solution.
Operator ?. read a property (calls a method) only if a left object is not void, otherwise returns undefined:
/* if object is void (null or undefined) then val = undefined,
  else val = property: */
val = object?.property;

/* if object is void (null or undefined) then val = undefined,
  else val is result of method call: */
val = object?.method();
The result can be supplemented by the or ( || ) operator to change undefined to alternate value:
/* if object is void (null or undefined) then val = alternate,
  else val = property: */
val = object?.property || alternate;

/* if object is void (null or undefined) then val = alternate,
  else val is result of method call: */
val = object?.method() || alternate;
Okay, let's rewrite the first example. Is not it, much shorter:
return some?.object?.that?.might?.not?.exist || 0;
5.5. Locking objects
Objects can be locked. After locking, nothing can change (or add) properties or methods of the object.
5.5.1. Operator @
This is an unary operator. It clones an object passed as a parameter (to the right of the operator) and then blocks the result of cloning. The object returned by the operator cannot be changed:
var obj = @ {
  x : 10,
  y : 20
};

obj.z = 30; // illegal operation!

The operator does not change the original object. Only its copy is locked:
var A = {
  x : 10,
  y : 20
};

var B = @A;

A.z = 30; // allowed
B.z = 30; // is not allowed

5.5.2. What happens when write to a locked object?
The interpreter will immediately throw an exception Exception.CanNotWritePropertyOfLockedObject :
var A = @ {
  x: 10,
  y: 20
};

try {
  A.z = 0;
}
catch(e) {
  if (e.instanceOf(Exception.CanNotWritePropertyOfLockedObject))
    print("exception!");
}
5.5.3. Why need to lock objects?
A classic example is the creation of enumerations. Suppose we have an object that contains only constants:
var Colors = {
  RED : "#FF0000",
  GREEN : "#00FF00",
  BLUE : "#0000FF"
};
Suppose that there is some function that takes the value of a constant as an argument:
setColor(Colors.RED);
And this will work, but nothing prevents changing the value of the constant:
Colors.RED = "#FF00FF"; // oops, now everything red will turn violet
To protect the object from accidental changes, you need to lock it. Just add @ :
var Colors = @ {
  RED : "#FF0000",
  GREEN : "#00FF00",
  BLUE : "#0000FF"
};

Colors.RED = "#FF00FF"; // exception!
All objects of the standard library (classes, functions, enums) are locked.
5.6. Threads
The Goat programming language supports threads. A thread of execution is the smallest sequence of programmed instructions that managed independently by a scheduler. In other words, thread is the ability to execute two or more sections of code at the same time.
Each running program contains at least one thread. Goat does not separate the "main" and "non-main" threads - each thread can initiate a new thread, and each thread can stop execution of another thread (if it has a pointer to this). The program ends only when all threads are completed.
5.6.1. Threads declaration
Threads are declared in the same way as functions, but the thread keyword is used instead of the function keyword:
var a = thread() {
  for (var i = 0; i < 10; i++)
    print('A');
};
5.6.2. Starting
To start a thread, need to call the run() method:
var a = thread() {
  for (var i = 0; i < 10; i++)
    print('A');
};

a.run();
Output:
AAAAAAAAAA
You can not re-run a thread that is already in progress.
You can run two, three, as many threads as you need, and they will run at the same time:
var a = thread() {
  for (var i = 0; i < 10; i++)
    print('A');
};

var b = thread() {
  for (var i = 0; i < 10; i++)
    print('B');
};

a.run();
b.run();
The output is something like this:
ABABABABABABABABABAB
Note: there is no guarantee of the order of execution of threads. The result may well be:
AABBBAAAABABBAABABAB
It is guaranteed that every thread will be executed from beginning to end.
5.6.3. Stopping
The running thread can be stopped by the stop() method:
var b = thread() {
  // this thread will never end if it does not stop!
  while(true)
    print('B');
};

b.run();
for (var i = 0; i < 10; i++)
  print('A');
b.stop();
The output is something like this:
BBABBABBABBBABBABBABBBABBABBABBBABB
6. Standard library
The standard library contains functions and classes for solving common tasks.
All the functionality of the standard library is divided into two parts: internal (as part of the interpreter core) and external.
The functionality of the inner part of the library is written in C++ language and is the minimum required set for solving most tasks. This functionality includes platform-dependent components, such as working with files. No additional modules are required to use the internal library, these classes and functions are always available.
The external library is written in Goat language. It is a set of files that contain separate classes for solving various tasks. To use this class from the library, you need to link the corresponding file using the import keyword.
6.1. Internal (core) library
6.1.1. Functions
6.1.1.1. Input/output
print ( object )
Converts an object to a string and sends this string to standard output.
Parameter:
  • object (any type): an object
Example:
print("Hello");
print(2 + 3);
print(0.01);
print(false);
print(null);
getc ( )
Reads one character from the standard input. Returns null if no characters (end-of-file is reached).
Example:
while(true) {
  var c = getc();
  if (c == null)
    break;
  print(c);
}
gets ( )
Reads characters from the standard input and stores them as a string until a newline character or the end-of-file is reached.
Example:
while(true) {
  var s = gets();
  println(s);
}
open ( fname, mode )
Opens a file.
Parameters:
  • fname (String): file name
  • mode (File.Mode): mode, one of: File.Mode.READ, File.Mode.WRITE or File.Mode.APPEND
Example:
var file = open("reference.xml", File.Mode.READ);
var data = file.read(256); // read first 256 bytes
See description of 'File' class for more details.
6.1.1.2. Other
defined ( object )
Returns true if the object is defined (i.e. not equals undefined ), and false otherwise.
Parameter:
  • object (any type): an object
Example:
var func = $(param) {
  if (!defined(param)) {
    return;
  }
  
  //...
};
clock ( )
Returns current system time in nanoseconds.
Example:
var wait = $(time) {
  var begin = clock();
  var diff = 0;
  do {
    diff = clock() - begin;
  } while(diff < time * 1000000000);
};

var i;
for (i = 5; i > 0; i--) {
  print("" + i + "\n");
  wait(1);
}

The example shows a simple implementation of delay and countdown using the 'clock' function. The function returns the time span value between the begin of the 'system epoch' (it depends from the platform) and the current time point. In itself, this value is useless, as a rule, the difference between the two clock values is used.
6.1.2. Classes
6.1.2.1. Input/output
6.1.2.1.1. File
The class for file reading/writing.
Files are opened by the open function (see above). The open function returns an object of File type, or null if the file could not be found or could not be open. The File class contains methods for reading/writing and some predefined fields, used in open and seek methods.
6.1.2.1.1.1. Methods
read ( count )
Reads a file and returns a ByteArray object with data.
Parameter:
  • count (Integer): number of bytes to read
Example:
var f = open("data.txt", File.Mode.READ);
var a = f.read(1024); // read first 1024 bytes
If the number of bytes exceeds the file size, the method will return as many bytes as it could read. The position indicator of the file is advanced by the total amount of bytes read.
eof ( )
Checks whether the end of file indicator associated with file is set, returning true if it is.
Example:
var f = open("data.txt", File.Mode.READ);
while (!f.eof()) {
  // read the file in chunks of size 1024 bytes
  var a = f.read(1024);
  // ...
}
position ( )
Returns the current value of the position indicator of the file.
Example:
var f = open("data.txt", File.Mode.READ);
f.seek(0, File.Origin.END);
var len = f.position(); // length of file
seek ( offset, origin )
Sets the position indicator associated with the file to a new position.
Parameters:
  • offset (Integer): number of bytes to offset from origin
  • origin (File.Origin): origin, one of: File.Origin.BEGIN, File.Origin.END or File.Origin.CURRENT
Example:
var f = open("data.txt", File.Mode.READ);
f.seek(0, File.Origin.END); // go to end of the file
var len = f.position(); // take position (position at the end is the length of the file)
f.seek(0, File.Origin.BEGIN); // now, go to begin
var data = f.read(len); // read the whole file
6.1.2.1.1.2. Fields
File.Mode
The object contains constants for file access mode, is used as an argument for open function.
File.Mode = {
  READ : ?,
  WRITE : ?,
  APPEND : ?
};
Usage:
var f = open("data.txt", File.Mode.READ);
The question mark ? means that in fact a constant is assigned a value (this is usually a number), but it depends on the implementation. Never use a value (magic number) instead of a constant!
Very bad example, please do not repeat it:
var f = open("data.txt", 0); // yes, it works now... but can fail later
File.Origin
The object contains constants for origin, is used as an argument for File.seek method.
File.Origin = {
  BEGIN : ?,
  END : ?,
  CURRENT : ?
};
6.1.2.2. Sequences
6.1.2.2.1. ByteArray
The class for storing an array of bytes.
The Goat interpreter does not have separated type for bytes representing. Integer type is used for this purpose. However, each Integer object takes much more memory than 1 byte. If you need to store an array of bytes, do not create an array of integers, use ByteArray class instead.
ByteArray class is used in files read/write operations.
6.1.2.2.1.1. Methods
length ( )
Returns length of the byte array.
push ( byte )
Appends a byte to the byte array.
Parameter:
  • byte (Integer): byte, valid values [0...255]
Example:
var a = new ByteArray();
a.push(0);
decodeUTF8 ( )
Decodes the byte array as UTF-8 encoded text and returns a string.
Example:
// open the file and decode it as UTF-8
var file = open("data.txt", File.Mode.READ);
file.seek(0, File.Origin.END); // go to end of the file
var len = file.position(); // take the length of the file
file.seek(0, File.Origin.BEGIN); // now, go to begin
var raw = file.read(len); // read the whole file
var text = raw.decodeUTF8(); // decode
6.1.2.2.2. StringBuilder
The class for strings constructing.
The Goat programming language has immutable strings. It prevents many errors, but in some cases constructing of long string takes a lot of time, because for each iteration Goat creates a new string. For example:
// some coordinates:
var c = { x: 10, y: 20, z: 30};

// build string:
var str = "X=" + c.x + ", Y=" + c.y + ", Z=" + c.z;
It works, yes, but it is not a better solution. Goat splits the long expression and creates a new string (which, in turn, involves the creation of a new array of characters, and copying of the original array) on each step:
"X=" + c.x
-> "X=10"
... + ", Y="
-> "X=10, Y="
... + c.y
-> "X=10, Y=20"
... + ", Z="
-> "X=10, Y=20, Z="
... + c.z
-> "X=10, Y=20, Z=30"
So, five strings will be constructed. What about thousands of strings? Say you have an array and you need to make a string. A lot of time, a lot of memory! Or, you can use StringBuilder.
// some coordinates:
var c = { x: 10, y: 20, z: 30};

// build string:
var b = new StringBuilder();
b << "X=" << c.x << ", Y=" << c.y << ", Z=" << c.z;
var str = b.toString();
Much better.
StringBuilder has an array to hold characters. This array grows when new items (characters, strings, etc) added. This class does not create a new string for each addition. Thus, the construction of a long string takes much less time and memory.
6.1.2.2.2.1. Methods
append ( object, count )
Appends string representation of object to the sequence.
Parameters:
  • object (any type): an object
  • count (Integer): optional, the number of times the object will be added
Example:
var b = new StringBuilder();
b.append("test");
b.append('#');
b.append(123);
b.append('*', 5);
print(b); // output: "test#123*****"
toString ( )
Returns a string representing the data in this sequence.
Example:
var b = new StringBuilder();
b.append("hello");
b.append(", ");
b.append("world");
var s = b.toString(); // contains "hello, world"
6.1.2.2.2.2. Operators
<<
Appends string representation of object to the sequence.
Example:
var b = new StringBuilder();
b << "test" << '#' << 123;
print(b); // output: "test#123"
This is a synonym for the append method, but using the operator instead of the method is more convenient.
6.2. External library
6.2.1. Containers
Containers are used to store data. A container is a grouping of some variable number of data items (possibly zero) that have some shared significance to the problem being solved and need to be operated upon together in some fashion.
Examples of containers include list, stack, queue, etc.
6.2.1.1. Stack
A stack is a data type that serves as a container of elements, with two principal operations: push , which adds an element to the container, and pop , which removes the most recently added element that was not yet removed.
Elements can be taken from the stack in the reverse order to how they were put there. Another name of the stack structure - LIFO ("last in, first out"). Additionally, a peek operation may give access to the top without modifying the stack.
6.2.1.1.1. Methods
empty ( )
Returns true if the stack is empty and false otherwise.
push ( object )
Adds an element to the stack.
Parameter:
  • object (any type): an object
pop ( )
Removes the most recently added element and returns it.
If the stack is empty, throws Stack.StackIsEmpty exception.
peek ( )
Returns the top element without modifying the stack.
If the stack is empty, throws Stack.StackIsEmpty exception.
iterator ( )
Returns an iterator pointing to the beginning of the stack.
6.2.1.1.2. Example
Code:
import "stack.goat";

var s = new Stack();

for (var i = 0; i < 5; i++)
  s.push(i);

while(!s.empty())
  print("" + s.pop() + "\n");
Output:
4
3
2
1
0
6.2.1.2. Iterator
An iterator is an object that enables to traverse a container. Each container inherits Iterable object which has iterator() method. This method returns an iterator object which points to the first item of the container (or points to nothing if the container is empty). An iterator object has methods for reading/writing data and also has next() method to move to next item. Each container implements its iterator, which has the above methods. Thus, regardless of the container (stack, list, etc.), we have a universal way to traverse a container and get/modify data.
6.2.1.2.1. Methods
valid ( )
Returns true if the iterators is valid (i.e. points to an item of the container) and false otherwise.
next ( )
Moves to the next container element.
read ( )
Returns value of the current item.
If the iterator is not valid, throws Exception.InvalidOperation exception.
write ( val )
Write (replace) value of the current item.
Parameter:
  • val (any type): a value
If the iterator is not valid, throws Exception.InvalidOperation exception.
iterator ( )
Returns an iterator pointing to the beginning of the stack.
6.2.1.2.2. Example
Code:
import "stack.goat";

var s = new Stack();

for (var v = 0; v < 5; v++)
  s.push(v);

for (var i = s.iterator(); i.valid(); i.next())
  print("" + i.read() + "\n");
Output:
4
3
2
1
0
6.2.2. Timer
The Timer class measures time intervals. At the end of the interval, a function (callback) is called. The setTimer() method calls a function once; the setInterval() method calls periodically. Also, the Timer class has several auxiliary classes for determining time intervals.
6.2.2.1. Classes
6.2.2.1.1. Timer.Duration
Base class for determining time intervals. Has a method:
getNanoseconds ( )
Returns the time interval, converted to nanoseconds.
6.2.2.1.2. Timer.Nanoseconds
Derived from Timer.Duration , determine the time interval in nanoseconds.
import "timer.goat"

var d = new Timer.Nanoseconds(50); // determine 50 nanoseconds

6.2.2.1.3. Timer.Microseconds
Derived from Timer.Duration , determine the time interval in microseconds.
6.2.2.1.4. Timer.Milliseconds
Derived from Timer.Duration , determine the time interval in milliseconds.
6.2.2.1.5. Timer.Seconds
Derived from Timer.Duration , determine the time interval in seconds.
6.2.2.1.6. Timer.Minutes
Derived from Timer.Duration , determine the time interval in minutes.
6.2.2.1.7. Timer.Hours
Derived from Timer.Duration , determine the time interval in hours.
6.2.2.1.8. Timer.Interval
An object returned from setInterval() method.
6.2.2.1.8.1. Methods
stop ( )
Stops a periodic function call.
6.2.2.1.8.2. Fields
ticks
Integer. The number of triggered calls, that is, how many times the function was called.
skipped
Integer. The number of skips.
If the setInterval() method does not have time to process the previous function call until the next call, the next call of the function is skipped.
6.2.2.2. Methods
The ability to measure small (up to nanosecond) time intervals always depends on the particular platform on which the interpreter runs.
setTimer ( callback, duration )
Calls the function (callback) once after a determined time has elapsed.
Parameters:
  • callback (Function): a function
  • duration (Timer.Duration): a duration (Timer.Seconds, Timer.Milliseconds etc.)
Example:
import "timer.goat";

print("begin... ");

Timer.setTimer($() {
  print("done!");
}, new Timer.Seconds(5));
The function is called in a separate thread. It runs concurrently with the main thread of the program. May need to synchronize (mutexes, etc.) when accessing some data.
setInterval ( callback, interval )
Calls the function (callback) periodically.
Parameters:
  • callback (Function): a function
  • interval (Timer.Duration): an interval (Timer.Seconds, Timer.Milliseconds etc.)
Example:
import "timer.goat";

print("begin...\n");

var c = 0;
var i = Timer.setInterval($() {
  print("" + c + "\n");
  c++;
}, new Timer.Seconds(1));

while(c < 10) {
  // wait for 10 seconds
}

i.stop();
The function is called in a separate thread. The setInterval() method tries to call a function (callback) at regular intervals. Namely, the moments of the beginning of a function call are located approximately at regular intervals. If the setInterval() method does not have time to process the previous function call until the next call, the next call of the function is skipped.
6.2.3. XML
Simple XML parser. For more info about XML format, please visit https://en.wikipedia.org/wiki/XML .
The parser takes a string that contains the source document. If you need to parse the file, you must first read and decode it using other methods. The document is recognized as a whole, the output is a tree of XML elements. If the document contains an error, the parser throws an appropriate exception.
6.2.3.1. Classes
6.2.3.1.1. XML.Element
The class that contains the data of one XML element. An XML element can contain attributes and child elements, thus, each element is the root of the element tree. The XML parser returns one root element that contains all document as a tree of elements.
6.2.3.1.1.1. Fields
tag
String. The element's tag. For example, after parsing the element:
<root>...</root>
the tag field will be contain the value "root".
attrib
Object, contains attributes. For example, after parsing the element:
<rectangle width="300" height="200">...</rectangle>
the attrib field will be contain the object {width:300,height:200} .
If the element does not have attributes, this field will contain an empty object.
content
An array containing child elements. A child element can be a string or an XML.Element type. For example, after parsing the element:
<list><elem_1>...</elem_1>Some text between elements<elem_2>...</elem_2></list>
the content field will be contain the array:
  • item 0: XML.Element containing "elem_1" tag and child elements;
  • item 1: string "Some text between elements";
  • item 2: XML.Element containing "elem_2" tag and child elements.
6.2.3.1.1.2. Methods
toString ( indent )
Converts XML tree to a string.
Parameter:
  • indent (String): If specified, this indentation will be added before each child element, for better readability of the document. If not specified, a compact document will be generated without indentation.
For example, let's сreate a simple XML tree:
<root>
  <first>Data of the first element</first>
  <second/>
  <third>
    <child>Data of the child element</child>
  </third>
</root>
To do this, write the following code:
import "xml.goat";

var root = XML.parse("<root><first>Data of the first element</first><second/><third><child>Data of the child element</child></third></root>");
Now convert the tree back into a string without indentation:
print(root.toString());
Output is:
<root><first>Data of the first element</first><second/><third><child>Data of the child element</child></third></root>
Сonvert the tree to a string again, but indented into two spaces:
print(root.toString(" "));
Output is:
<root>
  <first>Data of the first element</first>
  <second/>
  <third>
  <child>Data of the child element</child>
  </third>
</root>
Indentation can be not only spaces but also any other characters. Now let's try an indent, consisting of a vertical line and space ( | ):
print(root.toString("| "));
Output is:
<root>
| <first>Data of the first element</first>
| <second/>
| <third>
| | <child>Data of the child element</child>
| </third>
</root>
6.2.3.1.2. XML.Error
The class contains a description of the error that occurred in the case of parsing a non-valid document.
Consists of two fields:
type
Error type, string. The parser usually selects the type of error from the predefined set of strings:
XML.Error.INVALID_TOKEN : "invalid token",
XML.Error.EXPECTED_TAG_NAME : "expected tag name",
XML.Error.UNEXPECTED_END : "unexpected end",
XML.Error.END_TAG_MISMATCH : "end tag does not match the start tag",
XML.Error.UNCLOSED_END_TAG : "end element was missing the character \'>\'",
XML.Error.MISSING_EQUALS : "missing \'=\' sign between attribute and attribute value",
XML.Error.MISSING_STRING : "a string literal was expected",
XML.Error.DUPLICATE_ATTRIBUTE : "duplicate attribute",
XML.Error.UNKNOWN_ENTITY : "unknown entity",
XML.Error.INVALID_CHARACTER : "invalid character",
XML.Error.EXPECTED_CDATA_SEQUENCE : "expected <![CDATA[ sequence"
index
Integer, the character number (index) in the source line on which the error occurred.
6.2.3.2. Methods
parse ( str )
Parse the string and returns an XML tree.
Parameter:
  • str (String): the source string
Example:
import "xml.goat";

var root = XML.parse("<root><item>Data of the item</item></root>");
If XML document is not valid, throws XML.Error exception. If valid, returns XML.Element object contains root element.
7. In comparison with JavaScript
The Goat programming language based in general on JavaScript, but it has some differences.
Some samples are below.
7.1. Identifiers
JavaScript
The first character of an identifier must be a letter, or an underscore ( _ ), or a dollar sign ( $ ). Subsequent characters may be letters, digits, underscores, or dollar signs.
Goat
The first character must be a letter or an underscore ( _ ). Subsequent characters may be letters, digits or underscores.
Dollar sign used as a short replacement of function keyword:
var f = $(a, b) { };
it's the same as:
var f = function(a, b) { };
7.2. Keywords
The Goat programming language reserves several additional keywords:
Keyword Description
thread Declares a thread
import Imports a source file
debug (instead of debugger ) Stops the execution of Goat script, and switch the interpreter to debug (step-by-step) mode
7.3. Primitive types
JavaScript
A primitive data type is a data that is not an object and has no methods. There are 6 primitive data types: string, number, boolean, null, undefined, symbol. All primitives are immutable.
Goat
There are no primitive types. All data represented as objects. Each object except undefined has some methods. There are some predefined objects which are prototypes for primitive data, such as numbers or strings: Char , String , Integer , Real , Boolean , Void , Undefined and Null .
This programming language clearly distinguishes between strings (prototype is String ) and individual characters (prototype is Char ), as well as integers ( Integer ) and floating-point numbers ( Real ). These types have different set of methods and operators, but if necessary type can be converted to another:
var c = 'a'; // prototype of c is Char
var s = String.valueOf(c); // conversion to String
All other structures, for example, functions, threads, arrays etc have own prototypes ( Function , Thread , Array ).
7.4. Scope
JavaScript
There are two types of scopes: global and local. Variables defined inside a function are in the local scope. Variables defined inside of a block statement will remain in the scope they were already in. ECMAScript 6 introduced the let keyword. Contrary to the var keyword, the let keyword supports the declaration of local scope inside block statements.
var func = function() {
  var v = 0;
  // do something...
  if (true) {
    let v = 1; // local declaration
  }
};
If you re-declare a JavaScript variable in the same block, it will not lose its value.
Goat
There is no global scope. You can re-declare variable with the same name in inner block statement, it will be used only in this block.
var func = $() {
  var v = 0;
  if (true) {
    var v = 1;
    print(v); // output: "1"
  }
  print(v); // output: "0"
};
But, if you re-declare a Goat variable in the same block, it will lose its value.
7.5. The 'this' keyword
JavaScript
You must use the this keyword to refer to the field of own object:
var MyClass = function() {
  this.x = 0;
};

MyClass.prototype.getX = function() {
  return this.x;
};
Goat
You can use the this keyword to refer to the field of own object, but you must not do it in all cases. You can skip this keyword in the methods. But in some cases, this keyword cannot be avoided, for example, if you already have a local variable or an argument with that name, but you want to explicit read or write the property of the object, or, you can add new properties to own object (which are not yet there):
var MyClass = {
  init : $() {
    this.x = 0; // with 'this'
  },
  
  getX : $() {
    return x; // without 'this'
  }
};
7.6. Operators
The Goat language has no comparison operators === (equal value and equal type) and !== (not equal value or not equal type). Operators == and != works in most cases as === and !== operators in JavaScript.
The Goat language has not typeof and instanceof operators. Use instanceOf method instead:
print(13.instanceOf(Integer)); // output: "true"
The Goat language provides several new operators:
7.7. Operators overloading
JavaScript
Doesn't support.
Goat
You can use the operator as method name:
var Vector = {
  init : $(x, y) {
    this.x = x; this.y = y
  },
  toString : $() {
    return "X: " + x + ", Y: " + y;
  },
  "+" : $(vec) {
    return new Vector(x + vec.x, y + vec.y);
  },
  "*" : $(val) {
    return new Vector(x * val, y * val);
  }
};

var v1 = new Vector(100, 200);
var v2 = new Vector(200, 400);

print((v1 + v2).toString()); // output: "X: 300, Y: 600"
print(' ');
print((v1 * 5).toString()); // output: "X: 500, Y: 1000";
7.8. Multithreading
JavaScript
Doesn't support. There are some workarounds, say web workers, and, of course, functions setTimeout() and setInterval() .
Goat
There is thread keyword. It possible to declare any function as a separate thread.
var t0 = thread(){
  while(true) {
    print('A');
  }
};

var t1 = thread(){
  while(true) {
    print('B');
  }
};

t0.run();
t1.run();

// Output: "ABABABABABABAB...."
7.9. The 'new' keyword and constructors
JavaScript
Constructors are like regular functions, but we use them with the new keyword. If you inherit your object and the parent has a constructor, you need to call parent constructor to perform initialization logic.
var A = function() {
  // init something...
};

var B = function() {
  A.apply(this);
  // init something else...
};
B.prototype = new A();
Goat
There is special method init() . If method defined, interpreter call it. If method also defined in base object, interpreter call it first (order of calling constructors as in C++).
var A = {
  init : $() {
    // init something...
  }
};

var B = A -> {
  init : $() {
    // init something else...
  }
};

var obj = new B(); /* both init method will be called,
            first from A, second from B */
7.10. Inheritance
JavaScript
var A = function() {
  this.x = 0;
};

var B = function() {
  A.apply(this);
  this.y = 1;
};
B.prototype = new A();

var C = function() {
  B.apply(this);
  this.z = 2;
};
C.prototype = new B();
Nearly all objects in JavaScript are instances of Object , a typical object inherits properties (including methods) from Object.prototype .
Goat
The syntax is much simpler. Use operator -> :
var A = {
  x : 0
};

var B = A -> {
  y : 1
};

var C = B -> {
  z : 2
};
Goat language has not class (prototype) named Object (is the root of the class hierarchy in Java and prototype hierarchy in JavaScript). Objects have not a super-prototype. An object has prototype if it created from literal (for example, strings), or it created by new keyword, or if prototype(s) is explicitly specified when creating an object:
var A = { }; // A has no prototypes
var S = "hello"; // the prototype of 'S' is 'String'
var B = new A(); // the prototype of 'B' is 'A'
var C = B->{ }; // the prototype of 'C' is 'B'
7.11. Multiple inheritance
JavaScript
Is not supported. You can use some tricks (say mixins) but it is not true multiple inheritance.
Goat
Why not.
var A = {
  x : 0
};

var B = {
  y : 1
};

var C = [A, B] -> {
  z : 2
};
The solution of the problem of multiple inheritance ("the diamond problem"): Goat uses the list of prototypes to inherit from as an ordered list. The interpreter uses the first method it finds by depth-first searching.
7.12. Syntactic sugar
7.12.1. Null conditional operator
JavaScript
Doesn't support. Currently, it is proposal options, it will be supported later.
Goat
Operator ?. is added. Operator ?. read a property (calls a method) only if a left object is not void, otherwise returns undefined:
var value = user?.address?.street;