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
        • Video
        • 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(val,num)
      • .padEnd(val,num
      • .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
  • Syntax
  • Supported Types
  • Examples
  • Basic Type Declarations
  • Typing Object Properties
  • Type Enforcement
  • Working with Functions
  • Type Conversion
  • Benefits of Typed Variables
  • Notes

Was this helpful?

Edit on GitHub
  1. Basics

Typed Variables

OSL allows you to declare variables with specific types, providing type safety and better code clarity. This feature enables you to enforce that a variable or object property can only hold values of a specified type.

Syntax

For variables:

type variableName = value

For object properties:

type objectName.propertyName = value

Supported Types

OSL supports the following type annotations for variables:

  • string - Text values

  • number - Numeric values (integers and decimals)

  • boolean - Logical values (true/false)

  • array - JSON arrays

  • object - JSON objects

  • function - Function objects

  • any - Any type (default if no type is specified)

Examples

Basic Type Declarations

// Typed variable declarations
string name = "Alice"
number age = 30
boolean isActive = true
array items = [1, 2, 3]
object settings = { theme: "dark" }

// Attempting to assign the wrong type will cause an error
name = 42  // Error: Cannot assign number to string variable

Typing Object Properties

You can also type specific properties of objects:

// Create an object
user = {
  name: "Bob",
  age: 25,
  active: true
}

// Type a property
string user.name = "Charlie"  // Works fine
number user.age = 30          // Works fine

// This would cause an error
number user.name = 50  // Error: Cannot assign number to string property

Type Enforcement

Once a variable or property is typed, OSL enforces that type for all future assignments:

// Initial declaration with type
number score = 100

// Valid reassignments
score = 200      // Works fine
score = score + 50  // Works fine

// Invalid reassignments
score = "High"   // Error: Cannot assign string to number variable
score = true     // Error: Cannot assign boolean to number variable

Working with Functions

Typed variables work well with functions that expect specific types:

// Function that expects a number
def double(number val) (
  return val * 2
)

// Using typed variables with functions
number value = 5
result = double(value)  // Works fine

string text = "10"
result = double(text)   // Error: Function expected number but got string

Type Conversion

If you need to change a value's type, you can use conversion methods:

string textValue = "42"
number numValue = textValue.toNum()  // Convert string to number

number price = 19.99
string priceTag = price.toStr()      // Convert number to string

Benefits of Typed Variables

  1. Error Prevention - Catch type-related errors early

  2. Code Clarity - Make your intentions clear about what type a variable should hold

  3. Better Tooling Support - Enable better code completion and hints

  4. Self-Documenting Code - Types serve as documentation for your variables

  5. Improved Maintainability - Makes code easier to understand and modify

Notes

  • Type annotations are optional - you can mix typed and untyped variables

  • Type checking happens at runtime when assignments occur

  • Once a variable is typed, that type is enforced for the lifetime of the variable

  • Type annotations do not affect the variable's value, only what values it can accept

  • Using typed variables can help catch bugs early and make your code more robust

PreviousLocal ScopingNextMathematical Usage

Last updated 3 months ago

Was this helpful?