Najova

DocsGuides

Your own functions

Make a function once, then call it like any built-in. Functions keep long scripts short and easy to read.

tip.naja
$function[tip;bill;percent]
  $return[$round[$get[bill] * $get[percent] / 100;2]]
$endfunction

$print[Tip on 48.50: $tip[48.50;15]]
$print[Tip on 12: $tip[12;20]]
najova run tip.naja
Tip on 48.50: 7.28
Tip on 12: 2.4

The first value of $function is the function's name. The rest name the values it takes. $return gives a value back and leaves the function.

Missing values

If a call gives fewer values than the function names, the missing ones are nil. Use that for optional values:

greet.naja
$function[greet;who]
  $if[$get[who] == nil]
    $set[who;stranger]
  $endif
  $print[Hello, $get[who]]
$endfunction
$greet[Mia]
$greet
najova run greet.naja
Hello, Mia
Hello, stranger

A function can call itself

factorial.naja
$function[factorial;n]
  $if[$get[n] <= 1]
    $return[1]
  $endif
  $return[$get[n] * $factorial[$get[n] - 1]]
$endfunction
$print[$factorial[10]]
najova run factorial.naja
3628800