BSL:Manual: Difference between revisions
m (→Coding style: clarity) |
(→Files: as in BSL:Introduction, adding note that some game data types can trigger BSL too; please add any other types that we know of) |
||
Line 2: | Line 2: | ||
{{TOClimit|3}} | {{TOClimit|3}} | ||
==Files== | ==Files== | ||
When Oni loads a level, it also loads and parses all .bsl files in the folder in [[IGMD]] which contains that level's scripts (the name of the folder being specified by the level's [[ONLV]] resource). The code automatically begins running with the function called "main", regardless of which .bsl file it is found in (Oni's scripts always place it in a file | When Oni loads a level, it also loads and parses all .bsl files in the folder in [[IGMD]] which contains that level's scripts (the name of the folder being specified by the level's [[ONLV]] resource). The code automatically begins running with the function called "main", regardless of which .bsl file it is found in (Oni's scripts always place it in a file ending in "_main.bsl"). The code then flows through whichever functions are called by "main". You can also manually call any of those functions from the [[Developer Mode|developer console]] -- however, you cannot actually define variables or functions through the console. | ||
However, besides the "main" entry point in a level's BSL scripting, there are types of game data which store function names that are to be called upon certain events. For instance, characters can call script functions upon death, and trigger volumes can call functions when they are entered or exited. See [[CHAR]], [[OBD:BINA/OBJC/CONS|BINA CONS]], [[OBD:BINA/OBJC/DOOR|BINA DOOR]], [[NEUT]], and [[TRGV]] for all known places in the game data that can trigger BSL functions. | |||
Note that the optional [[IGMD/global|global]] folder is also loaded for all levels, but any function found in a .bsl file there will be stranded and only accessible by console unless you edit a function in some level's existing BSL file so that it calls your global function. | Note that the optional [[IGMD/global|global]] folder is also loaded for all levels, but any function found in a .bsl file there will be stranded and only accessible by console unless you edit a function in some level's existing BSL file so that it calls your global function. |
Revision as of 17:12, 24 December 2015
Oni's scripting language is called BSL. Like any typical scripting or programming language, BSL scripts consist of plain-text files which employ branching logic and various operators according to certain rules of syntax in order to process data using functions that act upon variables. If any of those terms are not familiar to you now, keep reading. If you found that sentence boringly obvious, then you should be experienced enough to get by with BSL:Introduction.
Files
When Oni loads a level, it also loads and parses all .bsl files in the folder in IGMD which contains that level's scripts (the name of the folder being specified by the level's ONLV resource). The code automatically begins running with the function called "main", regardless of which .bsl file it is found in (Oni's scripts always place it in a file ending in "_main.bsl"). The code then flows through whichever functions are called by "main". You can also manually call any of those functions from the developer console -- however, you cannot actually define variables or functions through the console.
However, besides the "main" entry point in a level's BSL scripting, there are types of game data which store function names that are to be called upon certain events. For instance, characters can call script functions upon death, and trigger volumes can call functions when they are entered or exited. See CHAR, BINA CONS, BINA DOOR, NEUT, and TRGV for all known places in the game data that can trigger BSL functions.
Note that the optional global folder is also loaded for all levels, but any function found in a .bsl file there will be stranded and only accessible by console unless you edit a function in some level's existing BSL file so that it calls your global function.
Syntax
As with natural languages such as English, there are rules about punctuation, spacing, and word order in BSL.
Statements
All code consists of discrete statements. These statements can be gathered into larger structures to create more efficient programs.
Statement separators
BSL accepts 2 statement separators: the semicolon (;) and the linebreak. The following pieces of code are equivalent:
dmsg("Statement 1"); dmsg("Statement 2");
and
dmsg("Statement 1"); dmsg("Statement 2");
and
dmsg("Statement 1") dmsg("Statement 2")
The third example is in old-style syntax, which is discussed under Old vs. new syntax.
Compound statements
Compound statements are groups of statements held together by a pair of curly braces:
{ dmsg("Statement 1"); dmsg("Statement 2"); dmsg("Statement 3"); }
The purpose of doing this is to group some statements under either a function declaration (see Declaration) or an "if" statement (see Conditional). Such a group of statements is referred to as a block, and is also said to be in a scope. Traditionally in programming, anything inside a certain level of shared braces can be seen from elsewhere within those braces, or from within a scope inside that scope, but not from a scope outside that scope. This allows careful management of which code can alter which data. In BSL's case, there are certain issues with scope not being respected (see the if statement section). Variables outside of all scopes (such as functions) are referred to as "globals".
Comments
Comments are notes from the programmer to explain some code. In BSL, the comment marker is the "#". Any text after that character is not interpreted as BSL. Comments are supposed to be placed after a line of code...
var int a = 0; # this global is also modified in my_cutscenes.bsl
...or above a line or block of code:
# The following block of code calculates the meaning of life if (...) { ... }
Do not using trailing comments when not ending statements with semicolons (see Old vs. new syntax for explanation).
In documentation outside of source code or script files, such as this page, comments are sometimes used to tell the reader something in a way that doesn't break the actual code, if the user should type it in exactly as it appears, comments and all.
Old vs. new syntax
BSL allows two kinds of syntax to be used somewhat interchangeably, one of which is lighter on punctuation requirements. There's the simpler style, called "old style":
dprint "Hello"
and the more strict style, called "new style":
dprint("Hello");
This dual syntax can make it more complicated to talk about the language, and you can also generate errors if you accidentally mix syntax. For instance, if you try to end a function call with a semicolon, but you don't use a C-style function call...
dprint "Hello";
...you'll get an error mentioning an "illegal token" (the semicolon) in an "old style" function call. There are also other potential pitfalls with "old style" syntax, such as the fact that trailing comments don't work:
dmsg "Hello" # this comment will disable the line below it a = 4
...and the fact that semicolons are always needed at the end of variable declarations:
a = 3 # this line is valid old-style syntax (except for this comment)... var int a = 3 # ...this line is not (even without this comment!)
Thus, it's recommended to consistently use the "new" style of BSL. It requires a bit more typing, but it creates safer and more readable code. For consistency, all code on this page is in new-style syntax besides the old-style examples above.
Coding style
There are other aspects of the language which are flexible, and yet not connected to the old-style/new-style division. For instance, the quotes around "Hello" can be left out in both syntax versions of the above calls to dprint() and dmsg(). You can also omit stating the type and parameters of a function (with "void" being assumed in their absence). You also do not need to enclose code after an if/else statement in curly braces if there is only a single line. None of these syntax choices are in conflict with the "new style" syntax.
Additionally, you can use whitespace and newlines in different ways:
if (counter eq 3) { # do something } else { # do something else }
The above is three lines shorter than the below, but look at the difference in readability with this standard style, used throughout most of Oni's BSL scripts:
if (counter eq 3) { # do something } else { # do something else }
Reserved words
Here are the keywords that have special meaning in BSL.
Declaration
Before using a function or a variable for the first time, you need to declare its name and data type.
var
var int a = 0;
See Variables for details on declaring variables.
func
func void spawn_team(void) { ... }
See Functions for details on declaring functions.
Type specification
When declaring a variable or defining a function, you need to state what type of data is contained in that variable or what kind the function works with.
void, bool, int, float, string
var int a = 0; func int spawn_team(int flag) { ... }
Besides "void" (used in function definitions to indicate "no type"), these are the types of data that can be assigned to variables, passed to functions, and returned by functions. See Data types for details on the types.
Conditional
if
The only conditional statement is "if", with optional follow-up statements "else if" and "else", discussed below.
if (a operator b) { # ... }
The condition in the parentheses needs to evaluate to "true" or "false". For examples of operators, see Operators.
The condition can technically also evaluate to an int value, which then is converted to true/false:
if (8 - 8) # evaluates to false because it is zero if (8 - 7) # evaluates to true because it is non-zero
Braces are optional when you only have one line of code under the "if" (this is also true for "else" and "else if", discussed below):
if (a > 0) spawn_enemy_at_flag(a); spawn_considered = true;
Here, "spawn_considered" will be set to true regardless of whether the "if" condition was true and spawn_enemy_at_flag() was run. Though it's nice to save the vertical space, the danger in omitting braces is writing something like this:
if (a > 0) spawn_enemy_at_flag(a); spawn_considered = true;
That indentation on "spawn_considered" is misleading; when glancing at this code, you might expect that "spawn_considered" only is changed if "a" is greater than zero. It could be that you even intended to add that line to the "if" statement but forgot to add braces. Always using braces around an "if" statement's body will prevent that mistake.
Be aware that, even with braces, BSL does not always respect scope for blocks of code under "if" statements; for instance, a "return" statement will fire even if the surrounding "if" condition is false (see Flow interrupt for an example). An even more alarming example of bad scope is this:
func void broken_if(void) { var int one = 1; var int two = 2; var bool one_equals_two = false; if (one eq two) # this condition will evaluate to false, but... one_equals_two = true; # ...this will still run if (one_equals_two) dprint("Uh-oh."); else dprint("Phew."); }
Bungie West was aware of this bug, and would work around it by making a variable global and then calling a function to modify that variable, since function calls will not fire out of scope:
var bool one_equals_two; func void fixed_if(void) { var int one = 1; var int two = 2; set_oet(false); if (one eq two) set_oet(true); if (one_equals_two) dprint("Uh-oh."); else dprint("Phew."); } func void set_oet(bool input) { one_equals_two = input; }
One very handy feature that you also won't see in Oni's game scripts is that you can use the logical operators "and" and "or" to string together multiple conditions:
if ((a < b) and (c > d)) { # ... }
If you want to express the opposite of some condition, you can use the "!" operator (also unused by Bungie West). The following two statements have the same meaning:
if (!one_equals_two) if (one_equals_two eq false)
There's no functional need for the "!"; it just saves space.
else
When an "if" statement evaluates as false, you can use "else" to perform an alternate action:
var int one = 1; var int two = 2; if (one eq two) { # these commands will not run } else { # these are the commands that will run }
Though "else" is not used in Oni's existing BSL scripts, it seems to work fine.
else if
As is common in other programming languages, you can also specify an "if" condition that should only be evaluated if the previous condition was false, by writing "else if":
if (error eq 0) dprint("Everything is fine."); else if (error eq 1) dprint("There are too many enemies to add one more."); else # handle all other possibilities dprint("Unknown error code!");
Often, programmers only use "else if" statements to save some CPU cycles. For instance, if you had a long string of "if" statements to handle different possible values for a variable, why should they all be evaluated once you have already found the one that is true? Imagine the above example, but with 30 possible values for "error". In reality, you won't find much benefit in trying to save cycles with BSL. However, "else if" can also simplify logic:
if (d eq 0) ... if (d eq 1) ... if ((n eq d) and (n > 0) and (d > 1)) ... if ((n eq 0) and (d > 1)) ...
In checking the condition of "n" and "d" in this example, we have to keep checking after the second statement whether "d" is greater than 1; otherwise, multiple "if" statements could evaluate to true and execute their code, but we only want to act on one of these possible situations. Using "else if" allows us to be confident that only one statement can run:
if (d eq 0) ... else if (d eq 1) ... else if (n eq d) ... else if (n eq 0) ...
Notice how we can shorten the logical tests without losing anything. "d" is still implicitly required to be above zero in statements 2-4, or else they will not even be evaluated.
Flow interrupt
Use these keywords to interrupt the execution of BSL.
return
On its own, "return" exits the function early. You can also place a variable or constant after the keyword to pass that value back to a calling function. The fact that "return" is not used in Oni's scripts might explain this bug:
var int one = 1; var int two = 2; if (one eq two) { return; # this could not possibly be reached... or could it? } else { # this code should run, right? }
The statements under "else" will never run. The "return" will actually kick in and the function will exit, even though the surrounding control statement did not evaluate to true.
However, "return" is still useful for returning data to a calling function; see the section on returning function values.
sleep
You can also delay a script using "sleep", passing it a number in ticks:
sleep(60); # pause execution of BSL at this point for one second
Note that you cannot have a sleep statement in a function that returns a value, probably to avoid variables being changed at unexpected times.
Loop
It is generally desirable in any program to be able to run the same code over and over, such as repeatedly spawning enemies. This is one of BSL's biggest limitations, as it has no conventional loop statement like C's "for" or "while", but there are two indirect methods for looping: (1) use "fork" on a function (see the section on looping functions), and (2) "schedule-repeat-every" (see Concurrency).
Multi-threading
fork, schedule-at, schedule-repeat-every
See Concurrency for the use of these keywords.
Obsolete
iterate over ... using ...
An unfinished feature, "iterate" was going to utilize "iterator variables", but these don't exist.
for
Whatever Bungie West's intention for this keyword, it doesn't do anything.
Operators
Here are all the operators you can use in BSL.
Assignment
Symbol | Name | Description |
---|---|---|
= | Equals | Sets the left-hand entity to the right-hand value. |
Note that "=" is not for checking if one entity is equal to another (see "eq" below for that).
Arithmetical
Symbol | Name | Description |
---|---|---|
+ | Add | Sums two numbers. |
- | Subtract | Deducts one number from another. |
You'll note that there is no multiplication or division. Bungie West was only concerned with creating enough scripting power to drive Oni, and they did not need "higher math" for this. See Data types to learn the details of how math works between different data types.
Relational
Symbol | Name | Description |
---|---|---|
eq | Equal to | Tests if two values are equal. |
ne | Not equal to | Tests if two values are different. |
> | Greater than | Tests if a number is greater than another. |
< | Less than | Tests if a number is smaller than another. |
>= | Greater than or equal to | Tests if a number is greater than, or equal to, another. |
<= | Less than or equal to | Tests if a number is smaller than, or equal to, another. |
Note: eq and ne work for strings too.
Logical
Symbol | Name | Description |
---|---|---|
! | Not | Logical Not. Gives the inverse of a bool. The same as saying "some_bool ne true". |
and | And | Logical And. |
or | Or | Logical Or. |
See the "if" section to learn how to use the logical operators.
Data types
When declaring a variable or a function (more on this under the Functions and Variables sections), you must specify the type of data it contains, accepts, or returns. You can choose from "bool" (can be true/false), "int" (can be any whole number), "float" (a value with a decimal point), or "string" (some text).
var int x; var bool happy_bomber = true; func string my_func(void) { ... }
Upon declaration, variables are automatically initialized to zero if no value is assigned explicitly, as in the above example with "x".
void
See Functions. Variables cannot be type "void".
bool
A Boolean number has one of two possible states. Thus, a bool can be either 1 or 0. You can also use the keywords "true" and "false".
var bool example = 1; func bool are_we_there_yet(void) { ... }
Giving a bool any value other than 0 will set it to 1. For instance, assigning a float to a bool will make the bool "true" unless the float value is 0.0, which will become "false".
int
A 32-bit signed whole number; that is, it can be positive, negative or zero, with a maximum value of 2,147,483,647 and a minimum value of -2,147,483,648.
var int example = -1000; func int get_enemy_count(void) { ... }
Note that the number wraps around, which means that once it passes its maximum or minimum value, it starts over from the other end. For instance, the function...
func void overflow_test(void) { var int overflow = -2147483648; overflow = overflow - 1; }
...will print "int32: 2147483647" to screen when it runs.
Adding a float or a bool to an int yields odd and very high results, even if the float or bool could in theory be seamlessly converted to an int. Assigning a float to an int correctly assigns the truncated integer to the int. Assigning a bool to an int works correctly, the bool being treated as either 0 or 1.
float
A floating-point number. Bungie West actually never used floats in their scripts for Oni, which explains why there are certain rough aspects to them. For instance, floats are limited to six decimal places of precision:
var float good_example = 10.5; # returns as "10.500000" var float too_precise = 3.141592653589793; # returns as "3.141593"
Thus, adding a value below the sixth decimal place to a float will have no effect, e.g. 3.000000 + 0.0000001 = 3.000000. Additionally, adding an int (or a bool) to a float has no effect:
func float test_float_addition(void) { var float add_to_me = 10.5; add_to_me = add_to_me + 1; return add_to_me; # returns "float: 10.500000" }
As opposed to proper float math:
func float float_test(void) { var float add_to_me = 10.5; add_to_me = add_to_me + 1.0; return add_to_me; # returns "float: 11.500000" }
string
A sequence of textual characters. BSL does not provide any functions for manipulating strings (concatenation, trimming, etc.).
var string example = "hello";
Trying to give a string a non-textual value (bool/int/float) gives the error "illegal type convertion" (sic). Trying to add two strings together simply crashes the game, rather than concatenating them as it would in some other languages. Adding a float to a string crashes too. Bools have no effect whatsoever.
Trying to add an int value to a string creates some cool and unexpected results. For instance, adding a number between 5 and 11 removes the first character from the string. A number greater than or equal to 12 removes the first two, and so on. Subtraction does not yield the reverse effect, even if you try it with the maximum int value (in which case, Oni crashes).
"(null)" is the value that strings assume when they have not been given a value yet; it cannot be assigned to a string manually.
func string string_test(void) { var string example; return example; # prints "string: (null)" }
Functions
A function is a block of code that can be accessed repeatedly whenever you want to perform a certain task. As in mathematics, functions can be passed input and can return output, though unlike in mathematics, they do not need to do either of those things in order to be useful, as BSL functions can affect external data by modifying global variables and by calling built-in functions which affect the game environment.
Defining
When beginning to define a function, you must begin the line with "func"...
func int some_function(int count, string enemy_name) { ... }
The input which the function accepts is listed between the parentheses, and separated by commas. First the type of the input is given ("int" in the first case), then the name of that input is given, which will be used within the function to refer to that input.
void
Functions do not need to accept or return data. When they don't, you use "void" to indicate this. Note that both "void"s can be omitted and will simply be assumed implicitly.
func void func_start(string ai_name) # Returns nothing to calling function, but accepts a string { ... }
func void music_force_stop(void) # Neither returns nor accepts any data { ... }
func music_force_stop # Same signature as previous function { ... }
Calling
You do not use "func" when calling a function. You simply name it:
some_function(3, "Jojo");
In this case, we are passing a constant value, three, into some_function, where it will be known as "count", and we are passing a constant string in as "enemy_name", but we could also have passed in variables by name:
var int num_heroes = 3; var string enemy = "Jojo"; some_function(num_heroes, enemy);
Recursive calling
A function can call itself, which is useful for various looping behavior, but a function can only call itself recursively up to about four times. Note that this limit is bypassed if you use "fork" to call a function from within itself, but this no longer counts as recursing because the logic will not complete in a predictable inside-to-outside order. For a non-recursive way to loop a function, see Looping.
Returning
As mentioned under Flow interrupt, "return" exits the function at that point. Because of the bug documented in that section, you cannot exit early from a function under some condition. Since "return" can thus only be placed at the end of a function, there is no point in using it at all unless you are going to pass back a value by placing a variable name after "return":
func int add_ten(int input) { var int the_result = input + 10; return(the_result); }
You would then use this function to set a variable, as follows:
some_number = add_ten(enemy_count);
Function return values can also be used in "if" statements to provide a true/false condition. If you have a function that returns a bool...
func bool is_it_safe(void) { var bool result = false; # do some investigation here and set result to true if it is safe return(result); }
...then it could be called this way in some other function:
if (is_it_safe()) dprint("It is safe."); else dprint("It is not safe.");
Looping
The following function creates a loop using "fork".
var int counter; func void increment_counter_to(int limit) { counter = 0; fork increment(limit); } func void increment(int limit) { counter = counter + 1; if (counter < limit) fork increment(limit); }
Note that calling the same function again before it finishes running the first time can have undesired effects. Using "sleep" before each call can prevent this overlapping execution. A short function like the example above should not need a "sleep" statement, as the remainder of the function after the "fork" call will complete in the same tick. But the more complex the function, the more ticks you will need to allow for it to complete, placing "sleep(1);", "sleep(3);", etc. before the "fork" call.
Concurrency
When you call a function, all the code inside that function will finish running before giving control back to the calling function; that is, unless you use one of the following keyword sets to run parallel "threads" of BSL at the same time. Unlike robust programming languages, there is very little control over BSL's version of "multi-threading", so see the caveats at the end of the "fork" section.
fork
If you call a function with "fork" before its name, the code below the function call continues without waiting for the function to return. If you place this sample code in a script and enter "fork_test" on the dev console, you will immediately see the output "int: 3" even though wait_for_a_second() is waiting for a second on its own thread. You can remove the "fork" keyword to see the difference.
func void fork_test(void) { var int counter = 0; fork wait_for_a_second(); var int enemies = count_enemies(); enemies; }
func int count_enemies(void) { return(3); }
func void wait_for_a_second(void) { sleep(60); }
As you can see, you can use forked functions to perform delayed actions without holding up the rest of the script; this not only allows the use of "sleep", but also any built-in functions that hold up BSL by design, like chr_wait_animation.
Also be aware that accidentally calling a nonexistent function using "fork" will crash Oni; when "fork" is not used, BSL will not recognize that the unknown function name represents a function, and thus will not attempt to call it and end up crashing.
Below are two types of uses for the "schedule" keyword. By scheduling a function call that operates on global variables and doesn't run unless a condition is true, you can simulate a "for" loop with these keyword sets.
schedule ... at ...
Allows you to schedule a function call a certain number of ticks in the future. Unused in Oni's scripts, but here's a working example:
schedule dmsg("BOOM") at 300; schedule dmsg("1...") at 240; schedule dmsg("2...") at 180; schedule dmsg("3...") at 120; schedule dmsg("4...") at 60; dmsg("5...");
You are not allowed to set a variable to the return value of a scheduled function call, just like you cannot use "sleep" in a function that returns a value. This is presumably to avoid unpredictable changes being made to variables that share scope with other code.
schedule ... repeat ... every ...
Allows you to schedule a function call to repeat x times at a rate of y ticks. Unused in Oni's scripts, but here's a working example:
schedule dprint("Is this annoying yet?") repeat 50 every 20;
Variables
A variable is a storage space in memory for a value that you will want to access at different times, and perhaps change over time as well.
Declaring
When declaring a variable, the statement must begin with "var" and the type of the variable...
var int i = 0;
Accessing
...but not when getting or setting its value later:
i = 4; var int c = i;
Built-in functions and variables
The above documentation for functions and variables explains how to create your own functions and variables. But, like any game, Oni provides access to a number of built-in functions and variables; these are used to write level scripts in BSL.
Built-in functions and variables such as "ai2_allpassive" and "ai2_blind" are hardcoded into Oni, that is, they were defined in C along with the rest of the engine code and then registered as accessible from BSL. This means that they are essentially black boxes: you are only given an external description of the input they take and the outcome of this input, but you cannot see the actual code behind them.
When using the developer console, you can manually call a built-in function, and can get and set the value of a built-in variable. However, you cannot actually define functions or declare variables through the console.
Built-in functions and variables are listed on BSL:List. They are grouped together by subject matter in the Scripting tasks category.