A method acts on a particular object, and can access its fields. A function within a type does not have automatic access to any object. Most of the time you could put a function outside of a type, and it will work the same. They are often put inside the type simply to help better organise your code - so that functions which are related to a particular kind of object are together.
In this simple example, we have a creature type, and creatures can fight each other, and take damage. Creatures will have as fields hitpoints, attack power, and a chance of doing double damage. They will have a method that works out how much damage to inflict, taking into account the bonus chance. They will have a method to take damage, which will reduce their hitpoints, and a method to die whose code I'm not writing (it depends how the creatures are stored, in a list/array etc)
How to battle them? You can do it with a function or method - I've shown both ways.
Type TCreature
Field hitpoints:Int, attackpower:Int, chance:Int
Method attack:Int()
Local roll:Int = Rand(0, 100)
If roll <= chance
Return attackpower * 2
Else
Return attackpower
End If
End Method
Method takedamage(damage:Int)
hitpoints :- damage
If hitpoints <= 0 Then die()
End Method
Method die()
'......
End Method
Function battle(attacker:TCreature, defender:TCreature)
Local punch:Int
punch = attacker.attack()
defender.takedamage(punch)
End Function
Method battle(victim:TCreature)
Local punch:Int
punch = attack()
victim.takedamage(punch)
End Method
End Type
'let's say we have two TCreatures, dragon and panther
'to make dragon attack panther using function
TCreature.battle(dragon, panther)
'to make dragon attack panther using method
dragon.battle(panther)
If you change attack() to a function, it won't work, because when it tries to access attackpower, it doesn't know which object it's associated with. Likewise if you make takedamage() a function, it won't know which creature it is supposed to reduce the hitpoints of.
The battle function is given both creature objects it needs to use. The battle method only needs to be given one object, as when you call it in the code, the method will already be associated with an object (dragon in this case) and so can access dragon's fields and methods automatically. So in Method battle we can just use attack() directly, whereas in Function battle we must specify with attacker.attack() which object we are talking about.
Note - you can't have a method and function within a type of the same name, so to use the example code you'd need to delete either the method or the function, according to which you prefer. (Or rename one of them)
I hope this clears it up a bit for you.
|