Menu
CoddyTech

Methods

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 5 of 65.

A function declared inside a class is a method: something the objects of the class can do. Like any function, a method can take parameters and return a value, and it can read and change the object's variables:

# score_board.gd
class_name ScoreBoard
extends RefCounted

var points: int = 0

func greet() -> void:
	print("Scoreboard ready")

func add(amount: int) -> void:
	points += amount

func doubled() -> int:
	return points * 2

func add_bonus() -> int:
	add(10)
	return points

Call a method on an object with a dot and pass the arguments in the parentheses:

var board := ScoreBoard.new()
board.greet() # Scoreboard ready
board.add(5)
print(board.doubled()) # 10
print(board.add_bonus()) # 15

Inside the class, a method calls another method of the same object by its name: add(10) in add_bonus() means self.add(10).

A method declared with -> void returns nothing, and one declared with -> int must return an int. Each call works on its own object: board.add(5) changes board.points and no other scoreboard.

The call must match the declaration: board.add() without an argument is an error reported before the program runs.

challenge icon

Challenge

Easy

Complete the methods of the class BankAccount in bank_account.gd. The account keeps its money in the variable balance, which starts at 0.

  • deposit(amount) adds amount to the balance
  • withdraw(amount) subtracts amount and returns true. When amount is more than the balance, it changes nothing and returns false
  • get_balance() returns the balance

The supplied code reads how many commands follow, then one command per line: deposit AMOUNT or withdraw AMOUNT. It prints a line for each command and the final balance. For deposit 50 and withdraw 80 it prints:

Deposited 50
Not enough money for 80
Current balance: $50

Your code goes in bank_account.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var account := BankAccount.new()
	var count := int(OS.read_string_from_stdin())
	for i in count:
		var parts := OS.read_string_from_stdin().split(" ")
		var amount := int(parts[1])
		if parts[0] == "deposit":
			account.deposit(amount)
			print("Deposited %d" % amount)
		elif account.withdraw(amount):
			print("Withdrew %d" % amount)
		else:
			print("Not enough money for %d" % amount)
	print("Current balance: $%d" % account.get_balance())
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler