Functions

There are two types of functions in Imba, methods and blocks.

Methods

def randomize Math.randomfunction randomize(){ return Math.random(); };
# A single argument def square num num * num// A single argument function square(num){ return num * num; };
# optional arguments def call url, method = 'GET' # do something here// optional arguments function call(url,method){ // do something here };
# Variadic arguments def race winner, *rest "{winner} beat {rest.join(', ')}"// Variadic arguments function race(winner){ var $0 = arguments, i = $0.length; var rest = new Array(i>1 ? i-1 : 0); while(i>1) rest[--i - 1] = $0[i]; return ("" + winner + " beat " + rest.join(', ')); };
# Optional arguments, with callback def save data, options = {}, &callback # do something here// Optional arguments, with callback function save(data,options,callback){ // do something here };
# Named parameters def animate values, ease: 'linear', duration: 1 # do something here// Named parameters function animate(values,pars){ // do something here };

Blocks

var square = do |v| v * vvar square = function(v) { return v * v; };

Blocks are like anonymous function expressions in JavaScript. They can be assigned and passed around. They have their own lexical scope / closure, but no dynamic scope. This means that self (implicit and explicit) inside the block still refers to the self of the outer scope.

Blocks can be passed in directly when calling functions, as the last argument.

[1,2,3,4].map do |num| num * 2 item.save do # callback trigger when item is saved? console.log 'item was saved'[1,2,3,4].map(function(num) { return num * 2; }); this.item().save(function() { // callback trigger when item is saved? return console.log('item was saved'); });