You may want to create your own functions to help organize your code and make your code more efficient.
Here's an example of a simple custom function that adds two numbers together:
function addNumbers(num1, num2) sum = num1 + num2 return sum end
In this function, we're using the function keyword to define a new function called
addNumbers. The function takes two parameters,
num2, which represent the two numbers we want to add together. Inside the function, we're adding the two numbers together and storing the result in a new variable called sum. Finally, we're using the
return keyword to send the sum variable back to wherever we asked the function to run.
To run this function, we could write some code like this:
result = addNumbers(5, 10) print(result) --prints 15
This code can be written anywhere else inside our game code. We are creating a variable named
resultand at the same time we're calling the
addNumbers function to run and we pass the numbers
10 to the function inside of the parentheses. The function then accepts those numbers in the exact order they were given, so that
10. This function will then create a variable named
num2 together, then return that sum as the result. So it will add
10, and save
sum. Then it returns
sum to where we called it.
The returned value from the
addnumbers function is then saved as
result. Finally, we're using the print function to display the value of result on the screen.
3 Apr 2023