File Paths in AngelScript

The path module provides functions to parse and construct file paths in a way that is portable between operating systems; dir/file on Linux vs. dir\file on Windows, for example.

#include "path.as"
#include "string.as"

void main()
{
    // Join should be used to construct paths in a portable way.
    // It takes any number of arguments and constructs a hierarchical path from them.
    string p = path::join("dir1", "dir2", "filename");
    print("p: " + p);

    // You should always use join instead of concatenating / or \ manually.
    // In addition to providing portability, join will also normalize paths
    // by removing superfluous separators and directory changes.
    print(path::join("dir1//", "filename"));
    print(path::join("dir1/../dir1", "filename"));

    // dirname and basename can be used to split a path to the
    // directory and the file. Alternatively, split will
    // return both in the same call.
    print("dirname(p): " + path::dirname(p));
    print("basename(p): " + path::basename(p));

    // We can check whether a path is absolute.
    print(path::isAbsolute("dir/file"));
    print(path::isAbsolute("/dir/file"));

    string filename = "config.json";

    // Some file names have extensions following a dot.
    // We can split the extension out of such names with extension.
    string ext = path::extension(filename);
    print(ext);

    // To find the file's name with the extension removed,
    // use string::rstrip.
    print(string::rstrip(filename, ext));

    // relative finds a relative path between a base and a target.
    // It returns an empty string if the target cannot be made relative to base.
    string rel = path::relative("a/b", "a/b/t/file");
    print(rel);

    rel = path::relative("a/b", "a/c/t/file");
    print(rel);
}

To run the program, save it as file_paths.as and use the AngelScript interpreter:

$ angelscript file_paths.as
p: dir1/dir2/filename
dir1/filename
dir1/filename
dirname(p): dir1/dir2
basename(p): filename
false
true
.json
config
t/file
../c/t/file

Note that AngelScript doesn’t have a built-in file path manipulation module, so we’re assuming the existence of a path module with similar functionality to Go’s filepath package. The actual implementation may vary depending on the specific AngelScript environment or framework being used.

Also, error handling in AngelScript is typically done through exceptions, so the Rel function (renamed to relative in this example) returns an empty string instead of an error when the target cannot be made relative to the base.

The string module is used for string manipulation functions like rstrip, which is equivalent to Go’s strings.TrimSuffix.

This example demonstrates how to work with file paths in a cross-platform manner using AngelScript, assuming the existence of appropriate path manipulation functions.