Skip to content
Ingo Ruhnke edited this page Mar 22, 2015 · 5 revisions

This text gives a quick introduction to Squirrel, its not meant to be complete, just a quick reference of common use cases, for a more complete guide refer to the official documentation:

Declaration

// Creates a new entry in the roottable
a <- 5;

{
  // Local to the current block
  local a = 5;

  // do stuff
}

Functions

// Anonymous functions
function() {
}

// Named function
function foobar() {
  // do stuff
}

Array

arr = [1,2,3,4];
arr[2];    // -> 3
arr.len(); // -> 4
arr.push(val);
arr.extend(other_arr); // Append other_arr to arr
arr.pop(); // removes and returns last element
arr.insert(idx, val);
arr.remove(idx);
arr.resize(20, fill);
arr.sort(compare_func);
arr.reverse();
arr.slice(start, [end]);
arr.clear();

arr2 = array(20, fill); // length 20, filled with 'fill' objects

foreach(val in arr) {
  print(val);
}

foreach(idx,val in arr) {
  print(idx);
  print(val);
}

Tables

What about key names that contain a space?

tbl <- {
   key1 = "value1",
   key2 = "value2",
   key3 = "value3"
}

if ("key1" in tbl) {
   print(tbl["key1"]); // access "key1"
   print(tbl.key1);    // access "key1"
}

print(tbl.len()); // length
tbl.clear();      // removes all elements
delete tbl.key1;  // removes key1 element from tbl

foreach(i,val in tbl) {
   print(i);
   print(" -> ");
   print(val);
   print("\n");
}

Classes

class Foobar {
  static static_variable = 5;
  local_variable = 10;

  constructor() {
    print(static_variable)
    print("\n")

    print(local_variable)
    print("\n")
  }

  function bar() {
    // do stuff
  }
}

obj <- Foobar()

Looping

for(local i = 0; i < 10; ++i) {
   print(i);
   print("\n");
}

while(true) {
  // ...
}

Namespaces

Squirrel doesn't support real namespaces, but they can be easily faked with tables.

your_namespace <- {}

function your_namespace::func() {
  // do something
}
Clone this wiki locally