calog/examples/scripts/languages/squirrel.nut

58 lines
1.4 KiB
Text

// A guided tour of Squirrel running on calog.
// Demonstrates: local variables, a function, an array with foreach, a table
// (map) with foreach, a simple class with a method, then the cryptoUuid native.
// Run: bin/calog examples/scripts/languages/squirrel.nut
// A local variable.
local engine = "Squirrel"
// A function.
function square(n) {
return n * n
}
// An array, iterated with foreach to build a table of squares.
local numbers = [1, 2, 3, 4, 5, 6]
local squares = {}
local total = 0
foreach (idx, value in numbers) {
local s = square(value)
squares[value] <- s
total = total + s
calogPrint("square of", value, "is", s)
}
calogPrint("sum of squares 1..6 =", total)
// A table (map), iterated with foreach over key/value pairs.
local record = {
language = engine
version = "3.x"
total = total
}
foreach (key, value in record) {
calogPrint("record[" + key + "] =", value)
}
// A simple class with a constructor and a method.
class Counter {
count = 0
constructor(start) {
count = start
}
function bump(by) {
count = count + by
return count
}
}
local counter = Counter(10)
counter.bump(5)
counter.bump(7)
calogPrint("counter after two bumps =", counter.count)
// Use the cryptoUuid native to mint a unique id.
local id = cryptoUuid()
calogPrint("generated uuid:", id)
// Tear down and exit cleanly (required -- calog does not auto-exit).
calogExit(0)