Classes

OSL supports a class-based object-oriented programming paradigm through its class syntax. Classes provide a way to create reusable object templates with properties and methods.

Basic Class Syntax

class ClassName (
  // Properties
  property1 = value1
  property2 = value2
  
  // Methods
  def methodName() (
    // Method body
    return value
  )
)

Creating and Using Classes

Classes in OSL are defined using the class keyword followed by the class name and a block of code enclosed in parentheses. Once defined, you can create instances of the class and access its properties and methods.

// Define a class
class Person (
  name = "Unknown"
  age = 0
  
  def greet() (
    // Using ++ to concatenate strings without spaces where needed
    return "Hello, my name is " ++ name ++ " and I am " ++ age ++ " years old."
  )
  
  def birthday() (
    self.age ++
    return age
  )
)

// Access class methods
log Person.greet()
// "Hello, my name is Unknown and I am 0 years old."

log Person.birthday()
// 1

log Person.age
// 1

Class Properties

Properties are variables defined within a class. They store the state of the class and can be accessed and modified through class methods or directly.

Private Properties

Properties that start with an underscore (_) are considered private and can only be accessed from within the class's methods. This provides a way to encapsulate internal state.

Inheritance

Classes can inherit properties and methods from other classes using the extends keyword. This allows for code reuse and the creation of specialized versions of existing classes.

When a class extends another class:

  • It inherits all properties and methods from the parent class

  • It can override properties by redefining them

  • It can add new properties and methods

Method Context

Within class methods, properties are accessed directly by name. The method operates in the context of the class instance, so this is not required (unlike in some other languages).

Cloning vs. Referencing Classes

When assigning a class to a variable, the default behavior is to create a clone (a copy) of the class. To create a reference instead, use the @= operator.

Examples

Simple Game Character Class

Class with Private Implementation

Notes

  • Classes in OSL are first-class objects

  • Class names typically use PascalCase by convention

  • Private properties (starting with _) provide encapsulation

  • Inheritance allows for code reuse through the extends keyword

  • By default, assigning a class creates a clone; use @= for references

Last updated

Was this helpful?