Skip to main content

Adding Static Objects

This section covers how to define and register static objects in Varjus. Static objects let you expose properties and methods to your scripts, making it easy to bind C++ logic into the scripting environment.

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.

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);
}

Properties should return values and are not allowed to take arguments. Methods, on the other hand, may take arguments and return computed values based on them. Use the provided Construct helpers for value creation instead of manually allocating memory.

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.

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...
}

After registration, the script will be able to reference "myObject" and interact with its members.

Using the Static Object in a Script

Once registered, the object becomes part of the global scope and can be used directly in your Varjus scripts. You can access properties as if they were fields and invoke methods just like regular functions.

Here’s a sample script that uses both:

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

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