Origin Scripting Language
  • Basics
    • Syntax
    • Types
    • The Execution Loop
    • Defining Variables
      • Clone Objects (=)
      • References To Objects/Variables (@=)
    • Assignment Operators
    • Local Scoping
    • Typed Variables
  • Operators
    • Mathematical Usage
      • Addition Operator (+)
      • Subtraction Operator (-)
      • Divide Operator (/)
      • Multiply Operator (*)
      • To The Power Of (^)
      • Modulo Operator (%)
    • Text Usage
    • String Concatenation Operator (+)
    • Array Operations
    • Comparative Operators
    • Logical Operators
    • Bitwise operators
    • Pipe Operator (|>)
    • Nullish Coalescing Operator (??)
  • Program Flow
    • If Statements
      • if truthy (
      • ) else if truthy (
      • ) else (
      • )
    • Switch Case
    • Iteration
    • While And Until
    • Dynamic OSL Execution
  • Arrays And Objects
    • Making Arrays Or Objects
    • Modifying An Array
    • Clone Objects And References
    • Object Operations
    • Object Property Shorthand
  • Environment
    • The Window System
    • Mouse Cursor
    • Camera
    • Sound System
    • Input Simulation
    • Running Other Languages
    • Notifications
    • Send Data Between Windows
    • Interfacing With Rightclick
    • Permissions
    • Files
      • What is a file? (in ofsf)
      • Creating Directories
      • open("file_path")
      • fileGet(int)
      • listFiles()
  • Storage
    • Save DB
    • Local DB
  • Custom Syntax
    • Commands
    • Methods
    • Functions
    • Inline
    • Lambda
    • Spread Operator
    • Typed Parameters
    • Classes
    • Promises
  • External
    • Make An Iframe App
  • Commands
    • Debugging
      • log "hello world"
      • warn "you should change this"
      • error "something went wrong"
      • void expression
    • Rendering
      • Basics
        • Color Commands
        • Color Picker
        • Modifiers
      • Draw Cursor
        • goto x y
        • set_x x
        • set_y y
        • change_x x
        • change_y y
        • change x y
        • loc a b c d
      • Elements
        • Canvas
        • Rectangle
        • Triangle
        • Icon
        • Text
        • Image
        • Input
        • Pen
        • Hitbox
        • Bar
        • Slider
      • ICN (Icon System)
        • Drawing Commands
        • Dynamic Icons
      • Clipping And Scrolling (frames)
      • 3D Rendering
  • Functions
    • Math
      • Math()
      • random(low,high)
      • min(num1,num2)
      • max(num1,num2)
      • lcm(num1,num2)
      • gcd(num1,num2)
      • sum(num1,..)
      • average(num1,..)
      • dist(x1,y1,x2,y2)
      • degtorad(angle)
      • radtodeg(angle)
      • noise(x, y, z)
      • octaveNoise(x, y, z, octaves, persistence)
    • Types
      • typeof(value)
      • symbol(name)
    • Encoding
      • encodeURIComponent(string)
      • decodeURIComponent(string)
      • btoa/atob(string)
    • function()
    • formatFileSize(bytes)
    • getGamepads()
    • import(path)
    • ouidNew()
    • parseFilePath(path)
  • Global Variables
    • Overview
    • System Information
    • User Information
    • Date and Time
    • Input State
    • Display and UI
    • Network
    • File System
  • Methods
    • Strings
      • .padStart(num,val)
      • .padEnd(num,val)
      • .startsWith(val)
      • .endsWith(val)
      • .wrapText(characters)
      • .trimText(characters)
      • .split(characters)
      • .count(val)
      • .replace(old,new)
      • .replaceFirst(old,new)
      • .oslTokenise()
      • .strip()
      • .toOrdArray()
      • .match(pattern)
      • Encoding
        • .encodeBin()
        • .decodeBin()
        • .encodeHex()
        • .decodeHex()
        • .encodeUTF16()
        • .decodeUTF16()
        • .encrypt(password)
        • .decrypt(password)
        • .ord()
        • .chr()
      • Hashing
        • .hashMD5()
        • .hashSHA1()
        • .hashSHA256()
        • .hashSHA512()
      • Case
        • .toLower()
        • .toUpper()
        • .toMixed()
        • .toTitle()
    • Keyboard
      • .isKeyDown()
      • .onKeyDown()
    • Utilities
      • .len
      • .not
      • .ask()
      • .reverse()
      • .first()
      • .last()
      • .append(val)
      • .prepend(val)
      • .insert(location,val)
      • .delete(location)
      • .concat(val)
      • .trim(idx1,idx2)
      • .left(num)
      • .right(num)
      • .contains(val)
      • .index(val)
    • Maths
      • .abs()
      • .invabs()
      • .log()
      • .ln()
      • .isPrime()
      • .sqrt()
      • .sign()
      • .chance()
      • .clamp(low,high)
      • .toBase(base)
      • Rounding
        • .round(places)
        • .ceiling()
        • .floor()
      • Trigonometry
        • .sin
        • .cos
        • .tan
        • .asin()
        • .acos()
        • .atan()
        • .radSin()
        • .radCos()
    • Iframes
      • .iframeNew()
      • .iframeGoto()
      • .iframeResize()
      • .iframeRedirect()
      • .iframeShow()
      • .iframeHide()
      • .iframeClose()
    • JSON
      • Arrays
        • .pop()
        • .shift()
        • .randomOf()
        • .sort(direction)
        • .sortBy(key,direction)
        • .swap(idx1,idx2)
        • .fill(value)
        • .join(characters)
        • .map(callback)
        • .filter(callback)
        • .some(callback)
        • .every(callback)
      • Objects
        • .getKeys(keys)
        • .getValues()
      • .JsonStringify()
      • .JsonParse()
      • .JsonFormat()
      • .JsonClean()
    • Types
      • .getType()
      • .isType(type)
      • .toNum()
      • .toBool()
      • .toStr()
    • Functions
      • .bind(context)
    • Networking
      • .httpGet()
      • .http(method,data,headers)
      • .getAsync()
      • .roturConnect()
      • .roturSend(msg,target)
      • Websockets
        • .newWebsocket()
        • .wsSend(msg)
        • .wsClose()
        • .wsOpen()
        • .wsHasnew()
        • .wsGetnext()
        • .wsGetcount()
    • Timestamp
      • .timestamp("convert-date")
      • .timestamp("component")
Powered by GitBook
On this page
  • Basic Class Syntax
  • Creating and Using Classes
  • Class Properties
  • Private Properties
  • Inheritance
  • Method Context
  • Cloning vs. Referencing Classes
  • Examples
  • Simple Game Character Class
  • Class with Private Implementation
  • Notes

Was this helpful?

Edit on GitHub
  1. Custom Syntax

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.

class Counter (
  count = 0
  
  def increment() (
    self.count ++
    return count
  )
  
  def reset() (
    self.count = 0
    return count
  )
)

log Counter.count
// 0
log Counter.increment()
// 1
log Counter.increment()
// 2
log Counter.reset()
// 0

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.

class User (
  username = "guest"
  _password = "secret"
  
  def login(pass) (
    if pass == _password (
      return true
    )
    return false
  )
  
  def getPassword() (
    return _password
    // Accessible within class methods
  )
)

log User.username
// "guest"
log User._password
// Error: Cannot access private property
log User.login("secret")
// true
log User.getPassword()
// "secret"

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.

// Base class
class Animal (
  type = "Unknown"
  sound = ""
  
  def makeSound() (
    return sound
  )
)

// Derived class
class Dog extends Animal (
  type = "Dog"
  sound = "Woof"
  
  def fetch() (
    return "Fetching the ball!"
  )
)

log Dog.type
// "Dog"
log Dog.makeSound()
// "Woof"
log Dog.fetch()
// "Fetching the ball!"

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

class Calculator (
  result = 0
  
  def add(num) (
    self.result = result + num
    // Directly access the result property
    return result
  )
  
  def subtract(num) (
    self.result = result - num
    return result
  )
)

log Calculator.add(5)
// 5
log Calculator.subtract(2)
// 3

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.

// Define a class
class Counter (
  count = 0
  
  def increment() (
    self.count ++
    return count
  )
)

// Clone the class (creates a separate copy)
myCounter = Counter
myCounter.count = 10

log Counter.count
// 0 (original unchanged)
log myCounter.count
// 10

// Create a reference to the class
sharedCounter @= Counter
sharedCounter.count = 5

log Counter.count
// 5 (original changed)
log sharedCounter.count
// 5

Examples

Simple Game Character Class

class Character (
  name = "Hero"
  health = 100
  strength = 10
  
  def attack() (
    return strength
  )
  
  def takeDamage(amount) (
    self.health -= amount
    if health < 0 (
      self.health = 0
    )
    return health
  )
  
  def isAlive() (
    return health > 0
  )
)

// Create a character
player = Character
player.name = "Alice"

// Use the character
log player.name
// "Alice"
log player.attack()
// 10
log player.takeDamage(25)
// 75
log player.isAlive()
// true

Class with Private Implementation

class SecureStorage (
  _data = {}
  
  def set(key, value) (
    self._data[key] = value
    return true
  )
  
  def get(key) (
    return _data[key] ?? null
  )
  
  def has(key) (
    return _data.contains(key)
  )
)

storage = SecureStorage
storage.set("username", "admin")
log storage.get("username")
// "admin"
log storage._data
// Error: Cannot access private property

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

PreviousTyped ParametersNextPromises

Last updated 9 days ago

Was this helpful?