Typing

Lunaris is a dynamic scripting language, which makes it perfect for modding. It’s easy and quick to write Lunaris code. Yet with typing it is possible to turn Lunaris into a static programming language. If no type is specified, then the type is considered any. We can apply any of the types as mentioned here. A type can be assigned to variables, functions, and even class fields & properties.

The code below does not have any types defined.

function output(input) {
    print(input)
}

Which is equivalent to

function output(input: any) : any {
    print(input)
}

The output function accepts any inputs, and it can return anything. We can refactor the example by being explicit

function output(input: string) : nil {
    print(input)
}
output("Hello World") // Hello World
output(2.1) // Error, as the output function only accepts a string

So as seen, typing is a various powerful feature of the language to be explicit in what types are supported.

Keyword: is

Whether typing is used or not, the is keyword is useful to check if a variable is of a certain type.

function Double(input: any) : any {
    // With the is keyword we check check if the input is a number
    if (input is number) {
        return input * 2;
    }
    return input + input;
}
Double(5) // 10
Double("Hello") // "HelloHello"

Union Type

A union type means a value can be one of several different types. If a value is string | number, then it can be either:

  • string
  • number
function Reverse(input: string | number) : string | number {
    if (input is number) {
        local reversed = 0
        while (number > 0) {
            local digit = number % 10
            reversed = reversed * 10 + digit
            number = math.floor(number / 10)
        }
        return reversed
    }
    local reversed = ""
    for (local i = #text; i >= 1; i--) {
        reversed = reversed + text[i]
    }
    return reversed
}
print(Reverse("lithrun")) // nurhtil
print(Reverse(26)) // 62
print(Reverse(true)) // Error, as reverse only accepts string or numbers

Examples

Let’s revist examples mentioned from other pages, and upgrade these to use typing.

Class

static class MathHelper {

    // Count how many times Add was called
    static GlobalCounter: number = 0;

    static function Add(a: number, b: number): number {
        MathHelper.GlobalCounter++
        return a + b
    }
}
MathHelper.Add(5, 10)
MathHelper.GlobalCounter = 0

MathHelper.GlobalCounter = false // Error, as GlobalCounter is a number

Function

function hello(name: string) : nil {
    print("Hello " + name)
}

hello("World") // Hello World
hello(true) // Error, as hello only accepts strings

Variables

local const maxHealth: number = 100;
local message: string = "Hello World";

message = 10; // Error, as message can only be a string

Categories:

Updated: