-
Notifications
You must be signed in to change notification settings - Fork 1
Syntax
%testVariable = 3;
The three most simple rules obeyed in the above code are:
The engine will parse code line by line, stopping whenever it reaches a semi-colon. This is referred to as a statement terminator, common to other programming languages such as C++, Javascript, etc. The following code will produce an error that may cause your entire script to fail: %testVariable = 3 %anotherVariable = 4;
%testVariable = 3%anotherVariable = 4;
if(%testVariable == 4) echo("Variable equals 4");
%testVariable = 3; The code is storing a value (3) in a local variable (%testVariable). It is doing so by using a common mathematical operator, the equal sign. TorqueScript recognizes the equal sign and performs the action just as expected. It does not care if there are spaces in the operation: %testVariable=3;
if(%testVariable == 4) echo("Variable equals 4"); CommentsThe last rule is optional, but should be used as often as possible if you want to create clean code. Whenever you write code, you should try to use comments. Comments are a way for you to leave notes in code which are not compiled into the game. The compiler will essentially skip over these lines.
// This comment line will be ignored // This second line will also be ignored %testVariable = 3; // This third line will also be ignored
Example: / While attending school, an instructor taught a mantra I still use:
// Why are you using multiple if statements. Why not use a switch$? / if(%testVariable == "Mich") echo("User name: ", %testVariable); VariablesUsageNow that you know the three most basic rules of writing code in TorqueScript, this is the best time to learn about variables. A variable is a letter, word, or phrase linked to a value stored in your game's memory and used during operations. Creating a variable is a one line process. The following code creates a variable by naming it and assigning a value: %localVariable = 3; You can assign any type value to the variable you want. This is referred to as a language being type-insensitive. TorqueScript does not care (insensitive) what you put in a variable, even after you have created it. The following code is completely valid: %localVariable = 27; %localVariable = "Heather"; %localVariable = "7 7 7";
%userName = "Heather"; %userAge = 27; %userScores = "7 7 7";
%userName = "Heather"; echo(%Username); In the above code, %userName and %Username are the same variable, even though they are using different capitalization. You should still try to remain consistent in your variable naming and usage, but you will not be punished if you slip up occasionally. Variable TypesThere are two types of variables you can declare and use in TorqueScript: local and global. Both are created and referenced similarly: %localVariable = 1; $globalVariable = 2; As you can see, local variable names are preceded by the percent sign (%). Global variables are preceded by the dollar sign ($). Both types can be used in the same manner: operations, functions, equations, etc. The main difference has to do with how they are scoped.
function test() { %userName = "Heather"; echo(%userName); }
$PlayerName = "Heather"; The above code makes full use of a global variable that holds a player's name. The first declaration of the variable happens outside of the functions, written anywhere in your script. Because it is global, you can reference it in other locations, including separate script files. Once declared, your game will hold on to the variable until shutdown. Data TypesTorqueScript implicitly supports several variable data-types: numbers, strings, booleans, arrays and vectors. If you wish to test the various data types, you can use the echo(...) command. For example: %meaningOfLife = 42; echo(%meaningOfLife); The echo will post the results in the console, which can be accessed by pressing the tilde key (~) while in game. NumbersTorqueScript handles standard numeric types 123 (Integer) 1.234 (floating point) 1234e-3 (scientific notation) 0xc001 (hexadecimal) StringsText, such as names or phrases, are supported as strings. Numbers can also be stored in string format. Standard strings are stored in double-quotes. "abcd" (string) Example: $UserName = "Heather";
'abcd' (tagged string) Tagged strings are special in that they contain string data, but also have a special numeric tag associated with them. Tagged strings are used for sending string data across a network. The value of a tagged string is only sent once, regardless of how many times you actually do the sending.
Example: $a = 'This is a tagged string'; echo(" Tagged string: ", $a); echo("Detagged string: ", detag($a)); The output will be similar to this: Tagged string: 24 Detagged string: The second echo will be blank unless the string has been passed to you over a network. String OperatorsThere are special values you can use to concatenate strings and variables. Concatenation refers to the joining of multiple values into a single variable. The following is the basic syntax: "string 1" operation "string 2" You can use string operators similarly to how you use mathematical operators (=, +, -, *). You have four operators at your disposal:
echo(%newString); OUPUT:
HelloWorld
Notice how the two strings are joined without any spaces. If you include whitespace, it will be concatenated along with the values: Example: %newString = "Hello " @ "World"; echo(%newString);
Example: %hello = "Hello "; %world = "World";
Example: echo("Hello" @ "World"); echo("Hello" TAB "World"); echo("Hello" SPC "World"); echo("Hello" NL "World"); BooleansLike most programming languages, TorqueScript also supports Booleans. Boolean numbers have only two values- true or false. true (1) false (0) Again, as in many programming languages the constant "true" evaluates to the number 1 in TorqueScript, and the constant "false" evaluates to the number 0. However, non-zero values are also considered true. Think of booleans as "on/off" switches, often used in conditional statements.
$lightsOn = true; ArraysArrays are data structures used to store consecutive values of the same data type. $TestArray[n] (Single-dimension) $TestArray[m,n] (Multidimensional) $TestArray[m_n] (Multidimensional)
Example: $firstUser = "Heather"; $secondUser = "Nikki"; $thirdUser = "Mich";
$userNames[0] = "Heather"; $userNames[1] = "Nikki"; $userNames[2] = "Mich";
$userNames[0] = "Heather"; What separates an array declaration from a standard variable is the use of brackets []. The number you put between the brackets is called the index. The index will access a specific element in an array, allowing you to view or manipulate the data. All the array values are stored in consecutive order.
[0] [1] [2] In our example, the data looks like this: ["Heather"] ["Nikki"] ["Mich"]
$userNames[1] = "Nikki"; $userNames[2] = "Mich"; The second array element (index 1) is assigned a different string value ("Nikki"), as is the third (index 2). At this point, we still have a single array structure, but it is holding three separate values we can access. Excellent for organization.
echo($userNames[0]);
[x] [x] [x] [x] [x] [x] [x] [x] [x]
$testArray[0,0] = "a"; $testArray[0,1] = "b"; $testArray[0,2] = "c";
[0,0] [0,1] [0,2] [1,0] [1,1] [1,2] [2,0] [2,1] [2,2] In our example, which progresses through the alphabet, you can visualize the data in the same way: [a] [b] [c] [d] [e] [f] [g] [h] [i] The first element [0,0] points to the letter 'a'. The last element [2,2] points to the letter 'i'. Vectors"Vectors" are a helpful data-type which are used throughout Torque 3D. For example, many fields in the World Editor take numeric values in sets of 3 or 4. These are stored as strings and interpreted as "vectors". "1.0 1.0 1.0" (3 element vector)
%position = "25.0 32 42.5";
%firstColor = "100 100 100 255"; echo(%firstColor); OperatorsOperators in TorqueScript behave very similarly to operators in real world math and other programming languages. You should recognize quite a few of these from math classes you took in school, but with small syntactical changes. The rest of this section will explain the syntax and show a brief example, but we will cover these in depth in later guides. Arithmetic OperatorsThese are your basic math ops.
Relational OperatorsUsed in comparing values and variables against each other.
Bitwise OperatorsUsed for comparing and shifting bits
{
pass logic
}
else
{
alternative logic
}
Remember how boolean values work? Essentially, a bool can either be true (1) or false (0). The condition (boolean) is always typed into the parenthesis after the "if" syntax. Your logic will be typed within the brackets {}. The following example uses specific variable names and conditions to show how this can be used:
// Global variable that controls lighting $lightsShouldBeOn = true; Brackets for single line statements are optional. If you are thinking about adding additional logic to the code, then you should use the brackets anyway. If you know you will only use one logic statement, you can use the following syntax:
// Global variable that controls lighting $lightsShouldBeOn = true; switch and switch$If your code is using several cascading if-then-else statements based on a single value, you might want to use a switch statement instead. Switch statements are easier to manage and read. There are two types of switch statements, based on data type: numeric (switch) and string (switch$).
switch(<numeric expression>) { case value0: statements; case value1: statements; case value3: statements; default: statements; } As the above code demonstrates, start by declaring the switch statement by passing in a value to the switch(...) line. Inside of the brackets {}, you will list out all the possible cases that will execute based on what value being tested. It is wise to always use the default case, anticipating rogue values being passed in.
switch($ammoCount) { case 0: echo("Out of ammo, time to reload"); reloadWeapon(); case 1: echo("Almost out of ammo, warn user"); lowAmmoWarning(); case 100: echo("Full ammo count"); playFullAmmoSound(); default: doNothing(); }
Switch$ Syntax: switch$ (<string expression>) { case "string value 0": statements; case "string value 1": statements; ... case "string value N": statements; default: statements; }
// Print out specialties switch($userName) { case "Heather": echo("Sniper"); case "Nikki": echo("Demolition"); case Mich: echo("Meat shield"); default: echo("Unknown user"); } LoopsAs the name implies, this structure type is used to repeat logic in a loop based on an expression. The expression is usually a set of variables that increase by count, or a constant variable changed once a loop has hit a specific point. For Loopfor Loop Syntax: for(expression0; expression1; expression2) { statement(s); } One way to label the expressions in this syntax are (startExpression; testExpression; countExpression). Each expression is separated by a semi-colon. Example: for(%count = 0; %count < 3; %count++) { echo(%count); } The first expression creates the local variable %count and initializing it to 0. In the second expression determines when to stop looping, which is when the %count is no longer less than 3. Finally, the third expression increases the count the loop relies on. While LoopA while loop is a much simpler looping structure compared to a for loop.
while(expression) { statements; }
Example: %countLimit = 0; FunctionsMuch of your TorqueScript experience will come down to calling existing functions and writing your own. Functions are a blocks of code that only execute when you call them by name. Basic functions in TorqueScript are defined as follows: // function - Is a keyword telling TorqueScript we are defining a new function. // function_name - Is the name of the function we are creating. // ... - Is any number of additional arguments. // statements - Your custom logic executed when function is called // return val - The value the function will give back after it has completed. Optional. The function keyword, like other TorqueScript keywords, is case sensitive. You must type it exactly as shown above. The following is an example of a custom function that takes in two parameters, then executes code based on those arguments.
function echoRepeat (%echoString, %repeatCount) { for (%count = 0; %count < %repeatCount; %count++) { echo(%echoString); } }
echoRepeat("hello!", 5);
Console MethodsConsole Methods are C++ functions that have been exposed to TorqueScript, which are attached to specific objects. Console FunctionsConsole Functions are written in C++, then exposed to TorqueScript. These are global functions you can call at any time, and are usually very helpful or important. Throughout this document, I have been using a ConsoleFunction: echo(...). The echo function definition exists in C++:
ConsoleFunction(echo, void, 2, 0, "echo(text [, ... ])") { U32 len = 0; S32 i; for(i = 1; i < argc; i++) len += dStrlen(argv[i]);
ObjectsThe most complex aspect of TorqueScript involves dealing with game objects. Much of your object creation will be performed in the World Editor, but you should still know how to manipulate objects at a script level. One thing to remember is that everything in TorqueScript is an object: players, vehicles, items, etc.
SyntaxEven though objects are originally created in C++, they are exposed to script in a way that allows them to be declared using the following syntax:
// In TorqueScript %objectID = new ObjectType(Name : CopySource, arg0, ..., argn) { <datablock = DatablockIdentifier;>
// Create a SimObject without any name, argument, or fields. $exampleSimObject = new SimObject();
// Create a SimObject with a custom field $exampleSimObject = new SimObject() { catchPhrase = "Hello world!"; };
// create a StaticShape using a datablock datablock StaticShapeData(ceiling_fan) { category = "Misc"; shapeFile = "art/shapes/undercity/cfan.dts"; isInvincible = true; };
Handles vs NamesEvery game object added to a level can be accessed by two parameters:
// In this example, CistFan is the name of the object new StaticShape(CistFan) { dataBlock = "ceiling_fan"; position = "12.5693 35.5857 59.5747"; rotation = "1 0 0 0"; scale = "1 1 1"; };
SingletonsIf you need a global script object with only a single instance, you can use the singleton keyword. Singletons, in TorqueScript, are mostly used for unique shaders, materials, and other client-side only objects. For example, SSAO (screen space ambient occlusion) is a post-processing effect. The game will only ever need a single instance of the shader, but it needs to be globally accessible on the client. The declaration of the SSAO shader in TorqueScript can be shown below: singleton ShaderData( SSAOShader ) { Object FieldsObjects instantiated via script may have data members (referred to as Fields) MethodsIn addition to the creation of stand-alone functions, TorqueScript allows you to create and call methods attached to objects. Some of the more important ConsoleMethods are already written in C++, then exposed to script. You can call these methods by using the dot (.) notation.
objHandle.function_name();
new StaticShape(CistFan) { dataBlock = "ceiling_fan"; position = "12.5693 35.5857 59.5747"; rotation = "1 0 0 0"; scale = "1 1 1"; };
// function - Is a keyword telling TorqueScript we are defining a new function. // ClassName::- Is the class type this function is supposed to work with. // function_name - Is the name of the function we are creating. // ... - Is any number of additional arguments. // statements - Your custom logic executed when function is called // %this- Is a variable that will contain the handle of the 'calling object'. // return val - The value the function will give back after it has completed. Optional.
function Samurai::sheatheSword(%this) { echo("Katana sheathed"); } When you add a Samurai object to your level via the World Editor, it will be given an ID. Let's pretend the handle (ID number) is 1042. We can call its ConsoleMethod once it is defined, using the period syntax:
1042.sheatheSword();
ConclusionThis guide covered the basics of TorqueScript syntax. Compared to other languages, such as C++, it is easier to learn and work with. However, no one is expected to become a TorqueScript master over night, or even in a week. You will most likely need to refer back to this documentation several times for reminders.
|