Strings

From Sven Co-op
Revision as of 19:30, 13 February 2025 by Outerbeast (talk | contribs)
Jump to navigation Jump to search

All text in Angelscript, and computing in general, is represented by strings. In AngelScript, the string class is what we use for that. This class uses an interface that differs from the one provided by the default Angelscript add-on, so you cannot rely on that for Sven Co-op.

Most of the string documentation is fairly straightforward, so this documentation will only cover a few items.

1 string_t

string_t is a special string type used to refer to strings allocated from the game's string pool. This type will automatically convert to and from the string type when needed, but you may sometimes have to manually convert it using value type conversion syntax:

// Convert to a string:
string szString = string( string_t_value );
string_t szString_t = string_t( "a string" );

Comparisons between string and string_t are legal:

string sText1 = "a string";
string_t stText2 = "a string";

if( sText1 == stText2 )
{
    // code
}

In most cases, a string_t object will implicitly cast to a string but its recommended to do this explicitly to avoid situations where the type may be ambiguous.

Reminder: string methods cannot be used on a string_t object, so you will have to cast it to string first. A large majority of entity attributes that are strings will be have the type "string_t" so keep this in mind.

2 printf

One of the features available in our API is a printf style formatting system. This allows you to provide a single string that contains placeholders where a varying number of arguments can be placed in them.

The standalone snprintf function allows you to format input into a specified output string:

string szResult;

if ( snprintf( szResult, "this %1 a %2 string\n", "is", "format" ) )
{
	g_Game.AlertMessage( at_console, szResult );
}

The syntax is fairly simple: every % symbol is considered a placeholder, with a number, starting at 1 for the first argument, referring to the argument that was passed in. If you want to use % itself, simply use %%. You can use the same argument multiple times, and it is not required to use each argument. Using a non-existent argument triggers a warning and causes formatting to fail.

You can pass in arguments that are primitives (boolean, integer, floating point) or strings (including string_t). Objects are output as memory addresses. Enums are also supported.

All functions that support the use of this formatting note this in their documentation. It is also possible to use this simply to copy strings by not specifying any placeholders, but that should be avoided due to the increased overhead in parsing the string.