extends Node2D
# Recursive function using factorial as example
const NUM: int = 8
func _ready():
print("Using Function 1 - " + str(NUM) +
"! Factorial is: " + str(factorial_one(NUM)))
print("Using Function 2 - " + str(NUM) +
"! Factorial is: " + str(factorial_two(NUM)))
# Standard function recursion
func factorial_one(n):
if n == 0:
return 1
else:
return n * factorial_one(n - 1)
# Using Ternary-if, one-liner
func factorial_two(n): return 1 if n == 0 else n * factorial_two(n - 1)
Output:
Using Function 1 - 8! Factorial is: 40320
Using Function 2 - 8! Factorial is: 40320
The GDScript code above shows how to use recursive function in Godot. For simplicity, we'll solve the factorial of a number. You can download the code here.
In this tutorial, it shows two factorial functions which derives the same results, the standard implementation and the other one uses ternary-if to shorten the code.
A recursive function calls itself during its execution. Thus, enabling the function to repeat itself many times.
This is the last tutorial for this basic series. In the next series, it will be all about arrays.
0 comments:
Post a Comment