Functions

A function is a reusable block of code that performs a specific tasks. A function can also optionally return a value

Function

In a earlier examples, you have seen the print("Hello World"). As a programmer, you don’t want to repeat yourself, so let’s make this a function.

function helloWorld() {
    print("Hello World")
}

The function itself doesn’t do anything until we invoke it, so let’s do that

helloWorld()
// Output: "Hello World"

Parameters

A function can also accept parameters, which are values inserted into the function that does something. Let’s see another example:

function hello(name) {
    print("Hello " + name)
}

hello("World")
hello("Lithrun")
// Output:
// Hello World
// Hello Lithrun

Optional Parameters

A parameter to a function can be made optional by assigning a default value to it. If the function is called without the parameters, then the default value is used.

function hello(name = "World") {
    print("Hello " + name)
}
hello() // Hello World

Return value

A function can also return a value.

function Add(a, b) {
    return a + b;
}

local c = Add(5, 10) // 15
local d = Add(-5, 10) // 5

Categories:

Updated: