bubblecode supports two kinds of reusable blocks: functions (which return a value) and handlers (which perform an action).
Functions
Define a function with function ... end. Use return to send a value back.
function double(x)
return x * 2
end double
say "double(21) =" && double(21)
say "double(7) =" && double(7)
Handlers
Handlers are defined with on ... end. They run statements but don’t return a value.
on greet name
say "Hello," && name & "! Welcome to bubblecode!"
end greet
greet("World")
greet("bubblecode Developer")
Recursion
Functions can call themselves. Classic examples:
Factorial
function factorial(n)
if n is less than 2 then
return 1
end if
return n * factorial(n - 1)
end factorial
repeat with i from 1 to 10
say i & "! =" && factorial(i)
end repeat
Fibonacci
function fibonacci(n)
if n is less than 2 then
return n
end if
return fibonacci(n - 1) + fibonacci(n - 2)
end fibonacci
repeat with i from 0 to 12
say "fib(" & i & ") =" && fibonacci(i)
end repeat
Combining functions and handlers
Functions and handlers can call each other freely.
function square(n)
return n * n
end square
on report value
say "The square of" && value && "is" && square(value)
end report
repeat with n from 1 to 6
report(n)
end repeat