Using Arguments
This documentation explains how to pass arguments to a script when executing it from C++.
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.
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!")
}));
}
Notes
- Use
Construct
methods to create values instead of manual allocation. - You can pass multiple values, including arrays and complex data structures.
- The
receiver
list will contain the arguments that the script will receive in themain(args)
function.
Passing Arguments to a Script
Once the callback is defined, pass it to ExecuteScript
when executing the script.
Example
#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());
}
}
Explanation
ExecuteScript(AddArgs)
ensures thatAddArgs
is invoked before execution, providing arguments to the script.- The script receives the arguments in the
args
parameter ofmain(args)
.
Accessing Arguments in a Script
When a script is executed with arguments, they can be accessed in the main(args)
function.
Example
fn main(args)
{
for (const arg : args)
console.log(arg); // Output: 420, "Hello!", [1, "Array hello!"]
}
Notes
- The
args
parameter will contain the values passed from C++. - Each value retains its original type.
- If no arguments are passed, avoid declaring
args
inmain()
to prevent errors.
Additional Considerations
- Flexibility: Use this mechanism to dynamically configure script behavior based on C++ input.