-
Notifications
You must be signed in to change notification settings - Fork 2
Functions
A major feature of the Ly language is its functions, which we will go over now.
Defining a function is simple:
<name>{<code>}
where <name>
is a single character denoting the name of your function, and <code>
is the body of your function.
Inside a function, code is executed just like a completely seperate Ly program. The only connection between a function and the main program is the input and output commands.
Instead of performing I/O from STDIN and STDOUT, a function manages I/O through the stack of the parent program.
An example function looks like this:
P{ns::[1-s%![l%!u;]p:l]}
This is a simple prime number checker program wrapped up in a function named P
that takes a single number as a parameter and pushes either 0
or 1
to the stack depending on if the number passed was a prime or not.
NOTE: If you give a function the same name as an existing function or built-in instruction, the old function/instruction will be overwritten.
Calling functions is just as simple as creating them:
<name>
where <name>
again is the name of the function.
The function is run like a normal program, with three differences:
- Whenever the function outputs, it is pushed to the stack of the parent program
- Whenever the function takes input, it is popped from the stack of the parent program
- There is no implicit input. When the parent stack is empty, taking input inside the function will yield 0.
Here is an example call of the prime number function:
p{i}
This will pop a number from the stack, and push 1
if it was prime and 0
otherwise.