This tutorial will show you the basics on how to configure the engine, compile a script, and then execute it. The code in this article is not complete, it only contains the relevant parts to explain the basic structure for using the script library. For complete source codes see the samples that come with the SDK.
In this tutorial a couple of add-ons are used to make the code easier. You are not required to use these in your own application, but they will most likely let you get your project up and running faster. You'll want to take a look at the rest of the add-ons later on to see what else may be useful for you.
Being an embedded scripting library there isn't much that AngelScript allows the scripts to do by themselves, so the first thing the application must do is to register the interface that the script will have to interact with the application. The interface may consist of functions, variables, and even complete classes.
Pay special attention to how the message callback is registered right after the engine is created. The message callback is used by the engine to give human readable error messages when something isn't working as it should, e.g. a registration is done incorrectly, or a script has an error that fails to compile. While you still need to verify the return codes, the message callback can give you valuable information that will let you figure out what is wrong without much effort.
After the engine has been configured, the next step is to compile the scripts that should be executed.
The following is our script that will call the registered print
function to write Hello world
on the standard output stream. Let's say it's stored in the file test.as
.
void main() { print("Hello world\n"); }
Here's the code for loading the script file and compiling it. The AngelScript engine itself doesn't have access to the filesystem so the loading the files has to be done by the application. Here we're going to use the script builder add-on, which does the loading of the script files, and some preprocessing, such as handling #include directives.
The last step is to identify the function that is to be called, and set up a context for executing it.
The exception handling above is very basic. The application may also obtain information about line number, function, call stack, and even values of local and global variables if wanted.
Don't forget to clean up after you're done with the engine.
The print function is implemented as a very simple wrapper on the printf function.