Using Arguments
This guide explains how to pass arguments from C++ to a Varjus script at runtime (the main
function).
Defining the Argument Callback
To pass arguments to a script, define a callback function that populates an IValues
container with the values you want to pass.
For example:
// This is what the macro looks like //
#define VARJUS_DEFINE_ARGS(Name, ctx, args)\
void Name(struct CProgramRuntime* const ctx, IValues& receiver)
///////////////////////////////////////
VARJUS_DEFINE_ARGS(AddArgs, ctx, receiver)
{
receiver.push_back(CIntValue::Construct(ctx, 420));
receiver.push_back(CStringValue::Construct(ctx, "Hello!"));
receiver.push_back(CArrayValue::Construct(ctx, {
CIntValue::Construct(ctx, 1),
CStringValue::Construct(ctx, "Array hello!")
}));
}
In this example, the callback creates a mix of values—including an integer, a string, and an array—and pushes them into the receiver list. These values are constructed using provided Construct methods, avoiding manual memory management. The list will be passed to the script’s main(args) function.
Passing Arguments to a Script
Once the callback is defined, pass it to ExecuteScript
when executing the script.
#include "varjus_api/varjus_api.hpp"
int main()
{
// Create a new execution state
Varjus::State state;
// Load libraries and the script...
// Execute the script with arguments
if (const auto returnValue = state.ExecuteScript(AddArgs)) {
fmt::print(std::cout, VSL("The program returned: {}\n"), returnValue->ToPrintableString());
}
}
When ExecuteScript(AddArgs)
is called, the runtime invokes your AddArgs function before script execution. This prepares the arguments that will be made available to the script’s main(args)
function.
Accessing Arguments in a Script
Once the script is invoked with arguments, they can be accessed through the args
parameter in the main function. Here's how that might look in a Varjus script:
fn main(args)
{
for (const arg : args)
console.log(arg); // Output: 420, "Hello!", [1, "Array hello!"]
}
Inside the script, the args
parameter will contain the values passed from C++. Each item preserves its original type, allowing the script to work with the data naturally. If you’re not passing arguments, simply omit the args
parameter from the main function to avoid errors.