References To Objects/Variables (@=)

The reference assignment operator (@=) in OSL creates a reference to an existing object or variable rather than creating a copy. This allows multiple variables to point to the same underlying data.

Syntax

targetVariable @= sourceObject

Description

By default, when you assign an object to a variable using the standard assignment operator (=), OSL creates a clone (a copy) of that object. The reference assignment operator (@=) changes this behavior, creating a reference to the original object instead.

When you use @=:

  • Changes to the referenced object affect all variables that reference it

  • No additional memory is used for storing duplicate data

  • The relationship persists until one of the variables is reassigned

Examples

Basic Reference Assignment

// Create an object
original = {
  value: 10
}

// Create a reference to the object
reference @= original

// Modify through the reference
reference.value = 20

// Both variables reflect the change
log original.value
// 20
log reference.value
// 20

Comparing Clone vs. Reference

References with Arrays

References with Classes

Breaking References

A reference is broken when you reassign either variable:

Use Cases

References are particularly useful for:

  1. Sharing data between different parts of your program

  2. Reducing memory usage when working with large objects

  3. Implementing observer patterns where multiple components need to react to changes in shared state

  4. Working with mutable data structures that need to be modified by different functions

Notes

  • Use @= when you want changes to be visible across multiple variables

  • Use = when you want independent copies that can be modified separately

  • References in OSL are similar to references or pointers in other programming languages

  • The reference relationship is not bidirectional - reassigning the original variable doesn't affect references to it

  • References work with all object types: objects, arrays, classes, and functions

Last updated

Was this helpful?