Subscripting
This section contains the classes and functions for compiling and running AngelScript code while a game is running, which is known as subscripting.
Subscripting lets a game load code that isn't part of it, such as levels, items or quests written by the game's developers or players, scripts that server administrators can change without restarting the server, or a console for running code while debugging. The code is compiled into a script module of its own, separate from the game's code in the nvgt_game module, and the game then calls the functions in it.
- script_module holds the code. Get one with script_get_module(), add code to it, build it and initialize its global variables with reset_globals(), then find its functions and global variables.
- script_function is a function of a module, which can be called with a dictionary of arguments or retrieved into a funcdef handle and called like any other function.
The code in a module can only use the parts of NVGT allowed by its access mask, set with script_module::set_access_mask(), so that code from players can be kept away from files, the network and the operating system. Functions of the game can be shared with a module by importing them, and classes with the shared keyword.
The Subscripting Tutorial in the manual explains these concepts in depth, with a complete example.
Classes
script_function
A function of a script module, which can be called dynamically and inspected.
Remarks:
script_function objects are returned by the methods of script_module such as get_function_by_decl(), and by script_module::compile_function().
There are two ways to call one. call() takes a dictionary of arguments and returns a dictionary holding the return value, which works with any function but is slow to write. retrieve() instead stores the function in a handle of a funcdef with the same signature, after which it can be called like any other function.
Methods
call
Call the function, passing its arguments in a dictionary.
dictionary@ script_function::call(dictionary@ args, array
Arguments:
dictionary@ args: the arguments, keyed by their position as strings starting at "1", such as
\{\{"1", 20}, {"2", "hello"\}\}, or null for a function without parameters.array
@ errors = null: if given, receives three elements if the call fails: the reason, such as the exception that was thrown, the call stack where it happened, and the call stack of the caller. int max_statement_count = 0: the most statements the function may run before it is stopped, which protects against code that never returns, or 0 to use the max_statement_count of the function's module, which is no limit unless you set one. A negative value means no limit even if the module has a default.
Returns:
dictionary@: the args dictionary, cleared and then holding the return value under the key "0" if the function returns something, or a new dictionary if args was null. null if the call failed.
Remarks:
Integer return values are stored as int64 and floats as double, so retrieve them into variables of those types. Arguments are converted to the parameter types where possible, and handles and objects must be of the parameter's class or derive from it.
Calling a script_function directly, as in func(args), does the same as call().
Example:
void main() {
script_module@ mod = script_get_module("example", 2);
mod.add_section("example", "string greet(const string&in name, int times) { string r; for (int i = 0; i < times; i++) r += \"Hello \" + name + \"! \"; return r; }\nvoid crash() { int[] a; a[5] = 1; }");
mod.build();
dictionary@ r = mod.get_function_by_name("greet").call(\{\{"1", "Sam"}, {"2", 2\}\});
string greeting;
r.get("0", greeting);
string[] errors;
mod.get_function_by_name("crash").call(null, errors);
alert("Results", greeting + "\n" + errors[0]);
}
get_decl
Get the declaration of the function.
string script_function::get_decl(bool include_object_name, bool include_namespace = true, bool include_param_names = true);
Arguments:
- bool include_object_name: whether to include the class name of a method, as in
player::move. - bool include_namespace = true: whether to include the namespace of the function.
- bool include_param_names = true: whether to include the names of the parameters.
Returns:
string: the declaration, such as int add(int a, int b).
Remarks:
The decl property gives the declaration with the class name and namespace but without parameter names.
get_declared_at
Find out where the function was declared.
string script_function::get_declared_at(int&inout row, int&inout column);
Arguments:
- int&inout row: receives the line of the declaration.
- int&inout column: receives the column of the declaration.
Returns:
string: the name of the section the function is in, or an empty string if it isn't known.
retrieve
Store the function in a handle of a funcdef with the same signature, so it can be called directly.
bool script_function::retrieve(?&out handle);
Returns:
bool: true if the signature of the funcdef matched the function and the handle was set, false otherwise.
Remarks:
Pass the handle with @, as in func.retrieve(@my_funcdef_handle). Calling through the handle is as fast as calling any other function and needs no dictionaries, which makes it the best way to call a function many times. The return and parameter types must match exactly. See script_module for an example.
Properties
decl
The declaration of the function, with its class name and namespace but without parameter names, such as int add(int, int).
const string script_function::decl;
is_explicit
Whether the function is a constructor or conversion operator declared explicit.
const bool script_function::is_explicit;
is_final
Whether the function is a method declared final, which derived classes can't override.
const bool script_function::is_final;
is_override
Whether the function is a method declared override.
const bool script_function::is_override;
is_private
Whether the function is a private method.
const bool script_function::is_private;
is_property
Whether the function is a property accessor, declared with the property keyword.
const bool script_function::is_property;
is_protected
Whether the function is a protected method.
const bool script_function::is_protected;
is_read_only
Whether the function is a const method, which doesn't change its object.
const bool script_function::is_read_only;
is_shared
Whether the function is shared between modules, declared with the shared keyword.
const bool script_function::is_shared;
line
The line the function was declared on, or -1 if it isn't known.
const int script_function::line;
name
The name of the function.
const string script_function::name;
namespace
The namespace of the function, or an empty string for the global namespace.
const string script_function::namespace;
script
The name of the section the function was declared in.
const string script_function::script;
script_module
A module of script code, separate from the game's own, that can be built from source code or bytecode at run time and whose functions and variables can then be used.
script_module@ script_get_module(const string&in name, int mode = 1);
Arguments:
const string&in name: the name of the module.
int mode = 1: 0 to only get a module that already exists, 1 to create it if it doesn't, or 2 to always create a new, empty one, discarding any existing module with the name.
Remarks:
script_module objects can't be created directly, they are returned by script_get_module(). A module stays in the engine until it is discarded with discard(), so getting a module by name again returns the same code.
The usual steps are to add the code with add_section(), choose which of NVGT's functions the code may use with set_access_mask(), build it with build(), initialize its global variables with reset_globals(), bind any functions it imports from the game with bind_all_imported_functions(), and then find its functions with get_function_by_decl() or get_function_by_name() and call them. See the Subscripting Tutorial in the manual for a full walk through, including how to share classes and functions between the game and the module.
Every method fails with a negative value or an empty result once the module has been discarded.
Example:
funcdef int calculator(int, int);
void main() {
script_module@ mod = script_get_module("calculator", 2);
mod.add_section("calculator", "int add(int a, int b) { return a + b; }\nint multiply(int a, int b) { return a * b; }");
mod.set_access_mask(1); // Only NVGT's most basic functions, see set_access_mask.
string[] errors;
if (mod.build(errors) < 0) {
alert("Error", join(errors, "\n"));
return;
}
// Call a function through a dictionary of arguments.
dictionary@ result = mod.get_function_by_decl("int add(int, int)").call(\{\{"1", 20}, {"2", 22\}\});
int64 sum;
result.get("0", sum);
// Or retrieve it into a funcdef handle and call it like any other function.
calculator@ multiply;
mod.get_function_by_name("multiply").retrieve(@multiply);
alert("Calculator", "20 + 22 = " + sum + ", 6 * 7 = " + multiply(6, 7));
mod.discard();
}
Methods
add_section
Add a section of code to the module, to be compiled by the next build().
int script_module::add_section(const string&in name, const string&in code, uint line_offset = 0);
Arguments:
- const string&in name: the name of the section, usually the filename it came from, which error messages refer to.
- const string&in code: the code of the section.
- uint line_offset = 0: a number added to the line numbers in error messages, for code that begins part way into a file.
Returns:
int: 0 or more on success, or a negative AngelScript error code.
Remarks:
Sections can't use #include or other preprocessor directives, as the code is given straight to the compiler.
bind_all_imported_functions
Bind every function the module imports from other modules, with statements such as import void update() from "nvgt_game";.
int script_module::bind_all_imported_functions();
Returns:
int: 0 or more if every imported function was found and bound, or a negative value otherwise.
Remarks:
This must be called after build() and before calling any code that uses the imported functions. The game's own module is called nvgt_game.
bind_imported_function
Bind one imported function to a function of your choice.
int script_module::bind_imported_function(uint index, script_function@ func);
Arguments:
- uint index: the index of the imported function, from 0 to get_imported_function_count() - 1.
- script_function@ func: the function to bind it to, which must have the same signature.
Returns:
int: 0 or more on success, or a negative value on failure.
build
Compile the sections added to the module, replacing any code it held before.
int script_module::build(array<string>@ errors = null);
Arguments:
- array
@ errors = null: if given, receives the error messages, one per array element, each giving the section, line, column and message.
Returns:
int: 0 or more on success, or a negative value if compilation failed.
Remarks:
The sections are discarded once built, so code must be added again to build the module a second time.
NVGT doesn't initialize the module's global variables when building it, so call reset_globals() after a successful build if the code has globals, or they hold empty values such as 0 and null handles.
compile_function
Compile a single function, optionally adding it to the already built module.
script_function@ script_module::compile_function(const string&in section_name, const string&in code, array<string>@ errors = null, bool add_to_module = false, uint line_offset = 0);
Arguments:
- const string&in section_name: a name for the code, which error messages refer to.
- const string&in code: the code of the function.
- array
@ errors = null: if given, receives the error messages, one per array element, each giving the section, line, column and message. - bool add_to_module = false: whether to add the function to the module, so that other code can call it and it can be found by name. Otherwise it can only be called through the returned handle.
- uint line_offset = 0: a number added to the line numbers in error messages.
Returns:
script_function@: the compiled function, or null if the code didn't compile.
Remarks:
This is handy for running a line of code typed by a user, such as in a debug console.
compile_global
Compile a single global variable and add it to the already built module.
int script_module::compile_global(const string&in section_name, const string&in code, array<string>@ errors = null, uint line_offset = 0);
Arguments:
- const string&in section_name: a name for the code, which error messages refer to.
- const string&in code: the declaration of the variable, such as
int lives = 3;. - array
@ errors = null: if given, receives the error messages, one per array element, each giving the section, line, column and message. - uint line_offset = 0: a number added to the line numbers in error messages.
Returns:
int: 0 or more on success, or a negative value if the code didn't compile.
discard
Remove the module and its code from the engine.
void script_module::discard();
Remarks:
Its functions can't be called after this, so be sure nothing still holds them. The memory is freed once nothing refers to the module's code.
get_bytecode
Save the compiled code of the module as bytecode, which can be loaded again with set_bytecode() without compiling it.
string script_module::get_bytecode(bool strip_debug_info);
Arguments:
- bool strip_debug_info: whether to leave out the debug information, such as line numbers, which makes the bytecode smaller but error messages less helpful.
Returns:
string: the bytecode, or an empty string if it couldn't be saved.
Remarks:
Bytecode can only be loaded by a build of NVGT that registers exactly the same functions and types, so it isn't suitable for storing code that must keep working across versions of NVGT.
get_function_by_decl
Find a function of the module by its declaration.
script_function@ script_module::get_function_by_decl(const string&in decl);
Arguments:
- const string&in decl: the declaration of the function, such as
int add(int, int). Parameter names may be left out.
Returns:
script_function@: the function, or null if the module has no function with that declaration.
Remarks:
This is safer than get_function_by_name(), as it also checks the return and parameter types, which must be right for the call to work.
get_function_by_index
Get a function of the module by its index.
script_function@ script_module::get_function_by_index(uint index);
Arguments:
- uint index: the index of the function, from 0 to get_function_count() - 1.
Returns:
script_function@: the function, or null if the index is out of range.
Remarks:
Together with get_function_count(), this lets every function of the module be listed.
get_function_by_name
Find a function of the module by its name.
script_function@ script_module::get_function_by_name(const string&in name);
Arguments:
- const string&in name: the name of the function.
Returns:
script_function@: the function, or null if the module has no function with that name or has several, in which case use get_function_by_decl().
get_function_count
Get the number of functions in the module.
uint script_module::get_function_count();
Returns:
uint: the number of global functions, not counting class methods.
get_global
Get the value of a global variable of the module.
any@ script_module::get_global(uint index);
Arguments:
- uint index: the index of the global, from 0 to get_global_count() - 1, as returned by get_global_index_by_name().
Returns:
any@: an any holding the value, or null if the index is out of range.
Remarks:
Integers are given as int64 and floats as double, as an any can't give back narrower numbers, so retrieve them into variables of those types. Objects are given as handles.
get_global_count
Get the number of global variables in the module.
uint script_module::get_global_count();
Returns:
uint: the number of globals.
get_global_decl
Get the declaration of a global variable of the module.
const string script_module::get_global_decl(uint index);
Arguments:
- uint index: the index of the global.
Returns:
const string: the declaration, such as int counter, or an empty string if the index is out of range.
get_global_index_by_decl
Find the index of a global variable by its declaration.
int script_module::get_global_index_by_decl(const string&in decl);
Arguments:
- const string&in decl: the declaration of the global, such as
int counter.
Returns:
int: the index of the global, or a negative value if there is none.
get_global_index_by_name
Find the index of a global variable by its name.
int script_module::get_global_index_by_name(const string&in name);
Arguments:
- const string&in name: the name of the global.
Returns:
int: the index of the global, or a negative value if there is none.
get_global_name
Get the name of a global variable of the module.
const string script_module::get_global_name(uint index);
Arguments:
- uint index: the index of the global.
Returns:
const string: the name, or an empty string if the index is out of range.
get_imported_function_count
Get the number of functions the module imports from other modules.
uint script_module::get_imported_function_count();
Returns:
uint: the number of imported functions.
get_imported_function_decl
Get the declaration of a function the module imports.
const string script_module::get_imported_function_decl(uint index);
Arguments:
- uint index: the index of the imported function.
Returns:
const string: the declaration, or an empty string if the index is out of range.
get_imported_function_index
Find the index of an imported function by its declaration.
int script_module::get_imported_function_index(const string&in decl);
Arguments:
- const string&in decl: the declaration of the imported function.
Returns:
int: the index, or a negative value if the module doesn't import such a function.
get_imported_function_module
Get the name of the module a function is imported from.
const string script_module::get_imported_function_module(uint index);
Arguments:
- uint index: the index of the imported function.
Returns:
const string: the name of the module, such as nvgt_game, or an empty string if the index is out of range.
reset_globals
Initialize every global variable of the module, or set them back to their initial values, by running their initializers.
int script_module::reset_globals(array<string>@ errors = null);
Arguments:
- array
@ errors = null: if given, receives the error messages, one per array element, each giving the section, line, column and message.
Returns:
int: 0 or more on success, or a negative value on failure.
set_access_mask
Choose which of NVGT's functions and classes the module's code may use.
uint script_module::set_access_mask(uint mask);
Arguments:
- uint mask: the subsystems to allow, as a combination of the NVGT_SUBSYSTEM flags from the nvgt_subsystems.nvgt include joined with |, or 0xffffffff for everything.
Returns:
uint: the previous access mask.
Remarks:
This must be called before build(). A new module only has access to the general subsystem, 1, so code using anything else, such as files, sound or the network, fails to compile until it is allowed. NVGT_SUBSYSTEM_SCRIPTING_SANDBOX is a reasonable choice for code from untrusted sources, as it allows no access to files, the network or the operating system.
set_bytecode
Load bytecode saved with get_bytecode() into the module, replacing any code it held.
int script_module::set_bytecode(const string&in code, bool&out debug_info_was_stripped, array<string>@ errors = null);
Arguments:
- const string&in code: the bytecode to load.
- bool&out debug_info_was_stripped: receives whether the bytecode was saved without debug information.
- array
@ errors = null: if given, receives the error messages, one per array element, each giving the section, line, column and message.
Returns:
int: 0 or more on success, or a negative value if the bytecode couldn't be loaded.
Properties
max_statement_count
The default for the most statements a function of this module may run before it is stopped.
uint script_module::max_statement_count;
Remarks:
This defaults to 0, which means no limit. It is used by script_function::call() and script_function::opCall() on any function of this module when they are not given a max_statement_count of their own, and it is stored with the module, so every script_module object for the same module sees the same value. Limiting the statements of code that came from somewhere you don't control protects the game from code that never returns.
name
The name of the module.
string script_module::name;
Remarks:
Changing it renames the module in the engine, so script_get_module() must then be given the new name.
Functions
acquire_exclusive_lock
Take AngelScript's exclusive lock, which stops other threads from changing the engine's shared state until it is released.
void acquire_exclusive_lock();
Remarks:
This is for advanced uses with threads, and must be followed by release_exclusive_lock(). Holding it while doing anything slow stalls every thread that needs the engine.
acquire_shared_lock
Take AngelScript's shared lock, which many threads can hold together but which keeps any of them from taking the exclusive lock.
void acquire_shared_lock();
Remarks:
This is for advanced uses with threads, and must be followed by release_shared_lock().
get_function_signature
Get the declaration of a function from a handle to it or from a funcdef.
string get_function_signature(?&in function);
Returns:
string: the declaration of the function, such as void on_hit(int).
Remarks:
An exception is thrown if what is passed isn't a function handle.
release_exclusive_lock
Release AngelScript's exclusive lock taken by acquire_exclusive_lock().
void release_exclusive_lock();
release_shared_lock
Release AngelScript's shared lock taken by acquire_shared_lock().
void release_shared_lock();
script_dump_engine_configuration
Write a description of every function, class, enum and property NVGT registers with AngelScript to a stream.
void script_dump_engine_configuration(datastream@ output);
Arguments:
- datastream@ output: the stream to write to, such as an open file.
Remarks:
The output is in the format of AngelScript's WriteConfigToStream, as read by tools such as AngelScript's offline compiler and editors that complete code. It isn't written by compiled games.
Example:
void main() {
file f("engine_config.txt", "wb");
script_dump_engine_configuration(f);
f.close();
alert("Done", "The engine configuration was written to engine_config.txt.");
}
script_get_module
Get a script module by name, creating it if needed.
script_module@ script_get_module(const string&in name, int mode = 1);
Arguments:
- const string&in name: the name of the module. NVGT's own code is in a module called nvgt_game.
- int mode = 1: 0 to only get a module that already exists, 1 to create it if it doesn't, or 2 to always create a new, empty one, discarding any existing module with the name.
Returns:
script_module@: the module, or null if mode is 0 and there is no module with the name.
Remarks:
See script_module for an example.