Skip to content

Instantly share code, notes, and snippets.

@neikeq
Last active August 22, 2016 17:28
Show Gist options
  • Select an option

  • Save neikeq/20823ccb7defd1680a91b33810c0c52a to your computer and use it in GitHub Desktop.

Select an option

Save neikeq/20823ccb7defd1680a91b33810c0c52a to your computer and use it in GitHub Desktop.
Duck typing example in GDScript. An adaptation of: https://en.wikipedia.org/wiki/Duck_typing#In_Python
class Duck extends Reference:
func quack():
print("Quack, quack!")
func fly():
print("Flap, Flap!")
class Person extends Reference:
func quack():
print("I'm Quackin'!")
func fly():
print("I'm Flyin'!")
func in_the_forest(mallard):
mallard.quack()
mallard.fly()
# Constructor
func _init():
in_the_forest(Duck.new())
in_the_forest(Person.new())
# Output:
# Quack, quack!
# Flap, Flap!
# I'm Quackin'!
# I'm Flyin'!
# Notes:
# Every file in GDScript is a class and there is no global scope nor main function, therefore our entry point in this example will be the constructor
# In this example, Duck and Person are nested classes and they extend Reference to make code clearer
# Otherwise, if extending Object (or nothing which is equivalent to extending Object) you would need to manually free them by calling .free()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment