Functions
Functions in Astra are defined with #f and closed with #ef. They support parameters, return values, overloading, and recursion.
Defining Functions
Use #f name() to define a function and #ef to close it:
#f greet()
write "Hello from Astra!"
#ef
greet() \\ Hello from Astra!
💡 Note: Functions use #ef to close — not ;. Only chain methods use ; to close.
Parameters
Pass values to functions using parameters:
#f greet(name)
write "Hello, " + name + "!"
#ef
greet("Alice") \\ Hello, Alice!
greet("Astra") \\ Hello, Astra!
Multiple parameters
#f add(a, b)
return a + b
#ef
#f introduce(name, age)
write name + " is " + age + " years old"
#ef
write add(10, 20) \\ 30
introduce("Alice", 30) \\ Alice is 30 years old
Return Values
Use return to send a value back to the caller:
#f square(n)
return n * n
#ef
result = square(5)
write result \\ 25
\\ Use directly in expressions
write square(4) + square(3) \\ 25
Multiple return points
#f classify(x)
if x < 0
return "negative"
;
if x == 0
return "zero"
;
return "positive"
#ef
write classify(-5) \\ negative
write classify(0) \\ zero
write classify(10) \\ positive
Return string
#f greet(name)
return "Hello, " + name + "!"
#ef
msg = greet("Astra")
write msg \\ Hello, Astra!
Function Overloading
Define multiple functions with the same name but different number of parameters. Astra automatically picks the right one:
#f add(a, b)
return a + b
#ef
#f add(a, b, c)
return a + b + c
#ef
write add(10, 20) \\ 30
write add(10, 20, 30) \\ 60
⚠️ Note: Functions with the same name must differ in parameter count. Same name + same count will cause a conflict.
Recursion
Functions can call themselves — Astra supports recursion with a 5000-call stack limit:
Factorial
#f factorial(n)
if n <= 1
return 1
;
return n * factorial(n - 1)
#ef
write factorial(5) \\ 120
write factorial(10) \\ 3628800
Fibonacci
#f fib(n)
if n <= 1
return n
;
return fib(n - 1) + fib(n - 2)
#ef
write fib(10) \\ 55
write fib(15) \\ 610
Countdown
#f countdown(n)
if n == 0
write "Done!"
return 0
;
write n
return countdown(n - 1)
#ef
countdown(5) \\ 5 4 3 2 1 Done!
Nested Function Calls
Functions can call other functions:
#f double(x)
return x * 2
#ef
#f quad(x)
return double(double(x))
#ef
#f sumSquares(a, b)
return square(a) + square(b)
#ef
#f square(n)
return n * n
#ef
write quad(5) \\ 20
write sumSquares(3, 4) \\ 25
Alias in Functions
Use aliasto share a global variable inside functions as a local copy. Changes inside the function don't affect the global:
score = 100 alias tempscore
#f bonus()
tempscore = tempscore + 50
write "Bonus score: " + tempscore \\ 150
#ef
bonus()
write score \\ 100 — unchanged
Attach & Modules
Import functions from other .astra files using attach:
\\ utils.astra has: #f add(a, b) return a + b #ef
attach "utils.astra"
write add(10, 20) \\ 30
\\ With alias to avoid conflicts
attach "math.astra" as math
write math.multiply(5, 6) \\ 30