-
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 takes input from parameters passed to it when it is called, and output is pushed to the stack of the main 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.
Calling functions is just as simple as creating them. In fact, the syntax is the same!
<name>{<parameters>}
where <name> again is the name of the function and <parameters> are the parameters you want to pass to it.
The syntax for parameters is comma-seperated numbers that will be passed to the function. There are also two special values you can pass: c and i.
The interpreter parses your parameters into a single string of input that will be parsed to the function, like so:
-
cwill be replaced by a value popped from the stack and turned into a character. -
iwill be replaced by a value popped from the stack. -
A number will be added directly to the string with a space at the end.
Then, the function is run like it is a normal program with the parsed string as input. Any time the function tries to print a value, it will be added to the stack of the main program instead.
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.