The VScript Book

Chapter 1.1: The Heart of Squirrel - Tables

In Squirrel, the most important data structure of all is the table. It's a collection of key-value pairs.

// Create a table to hold data about a personality core.
local core = {}

// Use '<-' to CREATE new key-value pairs (slots) using "dot notation".
core.name <- "Wheatley"
core.color <- "Blue"
core.isMoron <- true

// Use '=' to MODIFY existing slots.
core.isMoron = false // He's in charge now!

Using = on a key that doesn't exist will cause a script error. This is a feature, not a bug—it helps you catch typos!

Accessing Keys with Bracket Notation

Dot notation (core.name) is a clean shortcut, but it only works for keys that are simple text strings without spaces. For keys that are numbers, variables, or strings with special characters, you must use bracket notation.

local testData = {}
testData["first name"] <- "Doug" // String with a space requires brackets
testData[1] <- "This key is a number"
local keyVar = "status"
testData[keyVar] <- "Operational" // Using a variable as a key

printl(testData[1]) // Prints "This key is a number"

Checking for Keys with in

How do you safely check if a key exists in a table before you try to access it? With the in operator.

local glados = { 
    name = "GLaDOS", 
    neurotoxinLevel = 100 
}

if ("neurotoxinLevel" in glados) {
    printl("Neurotoxin is present.")
}

if ("moralityCore" in glados) {
    // This is false, so the block is skipped.
    printl("Morality core is present.")
}

Looping Through Tables

Just like with arrays, you can use a foreach loop to go through every key-value pair in a table. Note that the order is not guaranteed.

// Using the 'glados' table from the previous example
foreach (key, value in glados) {
    printl("GLaDOS's " + key + " is " + value)
}

// Console Output:
// GLaDOS's name is GLaDOS
// GLaDOS's neurotoxinLevel is 100

More Table Methods

Tables have a few built-in helper functions:

  • .len(): Returns the number of slots in the table.
  • .rawget(key): Gets the value for a key, but *does not* check the parent table (delegation, an advanced topic).
  • .clear(): Removes all slots from the table.