The VScript Book

Chapter 0.6: Organizing Code with Functions

A function is a named, reusable block of code that you can "call" whenever you want to run the code inside it. This makes your scripts clean, organized, and powerful.

Defining and Calling a Simple Function

// This DEFINES a function named TriggerAlarm. The code inside does not run yet.
function TriggerAlarm() {
    printl("ALERT! Neurotoxin levels critical.")
    // In a real scenario, you'd play a sound or flash a light here.
}

// This CALLS the function, executing the code inside it.
TriggerAlarm()

Passing Information In with Parameters

You can make functions more flexible by giving them parameters (also called arguments). These are special variables that receive values when the function is called.

// This function accepts one parameter: 'name'.
function Greet(name) {
    printl("Hello, " + name + ". You have been an excellent test subject.")
}

// Now we can reuse the function with different data.
Greet("Chell") // Prints "Hello, Chell..."
Greet("Wheatley") // Prints "Hello, Wheatley..."

Getting Information Back with return

Functions can send a value back to the code that called them. This is called a return value.

// This function takes two numbers and returns their sum.
function AddTwoNumbers(num1, num2) {
    local result = num1 + num2
    return result
}

// Call the function and store its output in a new variable.
local totalScore = AddTwoNumbers(50, 25) // totalScore is now 75
printl("The total score is: " + totalScore)

Functions as First-Class Objects

In Squirrel, functions are a data type, just like numbers and strings. This is a very powerful concept. It means you can store a function in a variable or table slot.

// Storing a function in a variable
local sayHello = function() { printl("Hello!") }
sayHello() // This calls the function.

// Storing a function in a table
local Actions = {}
Actions.Action1 <- function() { printl("Action 1!") }
Actions.Action1() // This also works.

The ability to treat functions as data is the foundation for many advanced scripting techniques you will learn later.