Built in Functions - ThornLang/JavaThorn GitHub Wiki

Built-in Functions and Methods

This page documents all built-in functions, methods, and properties available in ThornLang.

Table of Contents

Global Functions

print(value)

Outputs a value to the console.

print("Hello, World!")  // Hello, World!
print(42)               // 42
print(true)             // true
print(null)             // nil
print([1, 2, 3])        // [1, 2, 3]

Parameters:

  • value: Any value to print

Returns: null

clock()

Returns the current time in milliseconds since epoch.

start = clock()
// ... do some work ...
elapsed = clock() - start
print("Operation took " + elapsed + " ms")

Returns: number - Milliseconds since Unix epoch

Array Methods

Arrays in ThornLang provide several built-in methods for manipulation.

length

Property that returns the number of elements.

arr = [1, 2, 3, 4, 5]
print(arr.length)  // 5

empty = []
print(empty.length)  // 0

Type: Property (not a method)
Returns: number

push(element)

Adds an element to the end of the array.

arr = [1, 2, 3]
arr.push(4)
print(arr)  // [1, 2, 3, 4]

// Returns new length
newLength = arr.push(5)
print(newLength)  // 5

Parameters:

  • element: Value to add

Returns: number - New array length

pop()

Removes and returns the last element.

arr = [1, 2, 3]
last = arr.pop()
print(last)  // 3
print(arr)   // [1, 2]

// Empty array returns null
empty = []
result = empty.pop()
print(result)  // nil

Returns: The removed element or null if empty

shift()

Removes and returns the first element.

arr = [1, 2, 3]
first = arr.shift()
print(first)  // 1
print(arr)    // [2, 3]

// Empty array returns null
empty = []
result = empty.shift()
print(result)  // nil

Returns: The removed element or null if empty

unshift(element)

Adds an element to the beginning of the array.

arr = [2, 3, 4]
arr.unshift(1)
print(arr)  // [1, 2, 3, 4]

// Returns new length
newLength = arr.unshift(0)
print(newLength)  // 5

Parameters:

  • element: Value to add

Returns: number - New array length

includes(element)

Checks if the array contains a specific element.

arr = [1, 2, 3, 4, 5]
print(arr.includes(3))   // true
print(arr.includes(6))   // false

// Works with any type
strings = ["apple", "banana", "orange"]
print(strings.includes("banana"))  // true

Parameters:

  • element: Value to search for

Returns: boolean

indexOf(element)

Returns the index of the first occurrence of an element.

arr = [10, 20, 30, 20, 40]
print(arr.indexOf(20))   // 1
print(arr.indexOf(50))   // -1

// Works with any type
names = ["Alice", "Bob", "Charlie"]
print(names.indexOf("Bob"))  // 1

Parameters:

  • element: Value to search for

Returns: number - Index of element or -1 if not found

slice(start, end?)

Returns a shallow copy of a portion of the array.

arr = [1, 2, 3, 4, 5]

// With start only
print(arr.slice(2))      // [3, 4, 5]
print(arr.slice(0))      // [1, 2, 3, 4, 5] (full copy)

// With start and end
print(arr.slice(1, 3))   // [2, 3]
print(arr.slice(0, 2))   // [1, 2]

// Original array unchanged
print(arr)               // [1, 2, 3, 4, 5]

Parameters:

  • start: number - Starting index (inclusive)
  • end: number (optional) - Ending index (exclusive)

Returns: New array with selected elements

String Properties

length

Property that returns the number of characters.

text = "Hello"
print(text.length)  // 5

empty = ""
print(empty.length)  // 0

unicode = "🚀"
print(unicode.length)  // 2 (depends on encoding)

Type: Property (not a method)
Returns: number

Dictionary Methods

Note: Dictionary methods are planned for Issue #16 and not yet implemented.

Planned Methods

// Coming in a future release:
dict = {"a": 1, "b": 2}

// dict.keys()      // ["a", "b"]
// dict.values()    // [1, 2]
// dict.has("a")    // true
// dict.remove("a") // Removes key
// dict.size()      // 2
// dict.clear()     // Removes all keys

Number Methods

Numbers in ThornLang are primitives and don't have methods. Use global functions for mathematical operations:

// No methods on numbers
x = 42
// x.toString()  // Error!

// Use string concatenation instead
str = "" + x  // "42"

// Mathematical operations use operators
abs = x < 0 ? -x : x     // Absolute value
squared = x * x           // Square
root = x ** 0.5          // Square root

Object Methods

Objects created with class syntax can have custom methods:

class Rectangle {
    $ init(width: number, height: number) {
        width = width
        height = height
    }
    
    $ area(): number {
        return this.width * this.height
    }
    
    $ perimeter(): number {
        return 2 * (this.width + this.height)
    }
}

rect = Rectangle(10, 20)
print(rect.area())       // 200
print(rect.perimeter())  // 60

Type Checking

While not methods, you can check types using patterns:

// Check if something is an array
$ isArray(value) {
    // Arrays have push method
    return value != null && value.push != null
}

// Check if something is a string
$ isString(value) {
    // Strings have length but no push
    return value != null && 
           value.length != null && 
           value.push == null
}

print(isArray([1, 2, 3]))    // true
print(isArray("hello"))      // false
print(isString("hello"))     // true
print(isString([1, 2, 3]))   // false

Error Messages

When calling methods on wrong types, you'll see helpful error messages:

// Array method on non-array
x = 42
// x.push(1)
// Error: Cannot access property 'push' on primitive type 'number'.

// Unknown array method
arr = [1, 2, 3]
// arr.map($(x) => x * 2)
// Error: Array method 'map' is not defined.
// Available array methods: length, push, pop, shift, unshift, includes, indexOf, slice

// Property on null
value = null
// value.length
// Error: Cannot access property 'length' on null.

Performance Notes

  • Array methods are optimized in the VM
  • The length property is O(1) for arrays
  • push and pop are O(1) operations
  • shift and unshift are O(n) operations
  • includes and indexOf are O(n) operations
  • String concatenation creates new strings

Future Additions

The following are planned for future releases:

Array Methods

  • map() - Transform elements
  • filter() - Filter elements
  • reduce() - Reduce to single value
  • forEach() - Iterate with function
  • sort() - Sort elements
  • reverse() - Reverse order
  • join() - Join to string

String Methods

  • charAt() - Get character at index
  • substring() - Extract substring
  • toLowerCase() - Convert to lowercase
  • toUpperCase() - Convert to uppercase
  • trim() - Remove whitespace
  • split() - Split into array
  • replace() - Replace occurrences

Math Functions

  • Math.abs() - Absolute value
  • Math.floor() - Round down
  • Math.ceil() - Round up
  • Math.round() - Round to nearest
  • Math.max() - Maximum value
  • Math.min() - Minimum value
  • Math.random() - Random number

See Also