Skip to main content

Adding Static Objects

This documentation explains how to define and register static objects in Varjus. Static objects allow you to expose custom properties and methods to scripts, enabling deeper integration between C++ and Varjus.

Defining a Static Object in C++

Static objects in Varjus consist of properties and methods that scripts can access. Define them using VARJUS_DEFINE_PROPERTY, VARJUS_DEFINE_METHOD, and VARJUS_DEFINE_STATIC_OBJECT macros.

Example

VARJUS_DEFINE_PROPERTY(myProperty, ctx, _this) {
return CStringValue::Construct(ctx->m_pRuntime, "Property access from C++!");
}

VARJUS_DEFINE_METHOD(myMethod, ctx, _this, args) {
return CStringValue::Construct(ctx->m_pRuntime, std::format("myMethod: {}", args[0]->ValueAsString()));
}

VARJUS_DEFINE_STATIC_OBJECT(MyCustomObject, receiver) {
receiver.AddMethod("customMethod", myMethod, 1);
receiver.AddProperty("customProperty", myProperty);
}

Notes

  • Properties should return values and cannot take arguments.
  • Methods can take arguments and return computed values.
  • Always use Construct methods to create return values instead of manual allocation.
  • Ensure thread safety if objects will be accessed in a multithreaded environment.

Registering the Static Object in a State

To expose the static object to scripts, register it using the AddNewStaticObject method in a Varjus::State instance.

Method Declaration

__VARJUS_ND Success AddNewStaticObject(const VarjusString& name, const OptionalCtor<void>& constructor);

Parameters

  • name - The name of the object as it will appear in scripts.
  • constructor - A reference to your defined static object (e.g., MyCustomObject).

Example

int main()
{
// Create a new execution state
Varjus::State state;

// Register the static object
if (!state.AddNewStaticObject("myObject", MyCustomObject)) {
std::cerr << "Failed to register static object!\n";
return 1;
}

// Continue with the rest of the initialization...
}

Using the Static Object in a Script

Once registered, the object and its members can be accessed in a Varjus script.

Example

fn main()
{
// Access a property
console.log(myObject.customProperty); // Output: "Property access from C++!"

// Call a method
return myObject.customMethod("hello!"); // Output: "myMethod: \"hello!\""
}

Additional Considerations

  • Performance: Your code runs in C++ :)
  • Error Handling: You can always trust that you receive the same number of arguments as defined in AddMethod.
  • Thread Safety: If using callbacks in a multithreaded environment, ensure thread safety where necessary.