-
Notifications
You must be signed in to change notification settings - Fork 0
2. Immediate vs Precompiled
There are two different ways RIFT can operate in: immediate and precompiled.
Immediate means that the format string is parsed and evaluated at the same time, after which the AST (Abstract Syntax Tree) is discarded.
Precompiled allows you to save the AST and reuse it as many times as you want. This is more efficient when the format string does not change, since the parsing takes more time than evaluation (we're talking in nanoseconds, but on average parsing takes two-three times more than evaluation).
Here's how you can use the immediate mode:
std::string result = rift::format("Hello, {name}!", {
{"name", rift::Value::from("World")}
});
All errors are handled internally and script is cleaned up right after. Ideal for situations where you just need to mutate one string and not touch it after.
Now look at how precompiled mode works, which is a bit more complex:
auto res = rift::compile("Hello, {name}!"); // returns Result<Script*>
if (!res) {
// Parsing error occurred
std::cerr << res.getMessage() << std::endl; // display the error
} else {
rift::Script* script = res.getValue();
// you can pass a map of variables to the run method
std::cout << script->run({
{"name", rift::Value::from("world")}
}) << std::endl; // Output: "Hello, world!"
// or...
// you can add variables to the script itself and then run it without passing any variables
script->setVariable("name", "world");
std::cout << script->run() << std::endl; // Output: "Hello, world!"
// library gives away the ownership of the script to the user,
// so don't forget to delete the script after you're done with it to avoid memory leaks
delete script;
}
This allows us to store the parsed script and save precious microseconds of CPU time when evaluating it several times :D