Variable Types and Definition
Variables can be defined in two ways. The most common is to place a colon after the variable definition and then have the type name in full, while the alternative is to have a shorthand identifier after the variable definition.
The standard variable types are:
Full type Shorthand Description ------------------------------------------------------------------------ var : Integer var A whole number from -2147483648 to 2147483647 var : String var$ A sequence of characters/letters var : Real var# A decimal or floating-point number var : Element var! A special element (image, entity, sound, etc) var : Boolean var% A boolean value (TRUE or FALSE)
|
Maths, Logic and Precedence
Cobra uses the standard operators
( ) / * + - for simple mathematical operations, where brackets take the highest precedence and addition/subtraction have the lowest priority. A full table of precedence is listed below.
( ) brackets / division * multiplication Not binary NOT And binary AND Or binary OR Mod binary MOD Xor binary XOR + addition - subtraction < > = less than, greater than, equal to
|
Automatical Type Conversion
When performing a mathematical operation between two values of a different type (for example, adding a Real to an Integer, inserting an Integer inside a String), the right-hand value is converted to the same type as the left-hand value.
Values can be forced to convert from one type to another with the functions:
ToReal,
ToInt and
ToString.
MessageBox( 1 + 3.4 + 0.4 ) // 3.4 is converted to 3 // 0.4 is converted to 0 // the total value 1 + 3 + 0 is converted to the string "4" and displayed
MessageBox( 3.4 + 1 + 0.4 ) // 1 is converted to 1.0 // the total value 3.4 + 1.0 + 0.4 is converted to the string "4.8" and displayed
|
String, Integer and Real literals
A literal is a way of writing a number or string in a way that the compiler and language can understand. If you were to say
a = 3 then
3 is an integer literal.
String literals are written in either
'single quotes' or
"double quotes".
Integer literals are written as standard whole numbers.
Real literals are written as numbers with a decimal point, for example
5.0.
Boolean literals are written as the constants
TRUE and
FALSE.
Hexadecimal integer literals are written with a dollar sign before the value, such as
$FF808080.
Binary integer literals are written with a percentage sign before the value, such as
%10101100.
It is important to remember the difference between Integer and Real literals when performing maths operations. The following code is incorrect:
Program Var a, b : Real Begin b = 1.4 a = 5 + b MessageBox(a) End
|
5 is an integer, so the value of
b is converted to an Integer before being added to 5, and so
a becomes 6.0 instead of 6.4 as it ought to be.