Functions inside objects questions

Get help with using AutoHotkey and its commands and hotkeys
A_Perry_1984
Posts: 76
Joined: 07 Dec 2018, 12:08

Functions inside objects questions

30 Nov 2019, 10:52

I am just now starting to get the grasp using arrays and objects, and would like to better understand them. The tutorial is great, but I find it easier to learn when I have real examples.
Can someone provide some simple examples of when functions inside objects come in handy?
Is a method just a function inside an object?
When would you want to use a reference to a function inside an object vs calling the function directly?

Thanks for any help.
User avatar
Chunjee
Posts: 515
Joined: 18 Apr 2014, 19:05
GitHub: Chunjee

Re: Functions inside objects questions

01 Dec 2019, 10:16

The most common object with methods attached to it is a class. Classes are very useful when building a larger app with object-oriented architecture. For the most part objects allow state and logic to act as one. Like anything this has benefits and drawbacks.
For example you want to create a lot of {{x}} objects and each one needs to remember things about itself (has it's own data/actions) Instead of juggling variables and global scope for each instance of the object, you just create an instance of each object.

For example building a game with 20 NPCs. You know each NPC needs some data about itself. Their name, hp, etc. They also have actions; maybe move_here(), give_money(), etc.

Code: Select all

class npc {

    ; class attributes
    static hp := 100
    static gold := 200

    move_here(parameter_x, parameter_y) {
        ; move somewhere
    }

    give_money(parameter_recipient, parameter_ammount) {
        if (this.gold > parameter_ammount) {
            ; give money
            this.gold := this.gold - parameter_ammount
        } else {
            ; not enough money do to that
            this.say("Sorry " parameter_recipient ", I don't have enough to pay you!")
        }
    }

    say(parameter_text) {
        ; msgbox, % parameter_text
    }
}

Realworld example: fist class I ever wrote. https://github.com/Chunjee/Wop_Plugin-Health-Monitor/blob/master/Plugins/DVR.ahk#L88
User avatar
Chunjee
Posts: 515
Joined: 18 Apr 2014, 19:05
GitHub: Chunjee

Re: Functions inside objects questions

01 Dec 2019, 10:22

Something I wish I had when I was first discovering arrays and objects: https://biga-ahk.github.io/biga.ahk/#/

biga.ahk itself is a class, it doesn't have much data so there's no real point to having multiple instances like the 20 NPC example. It has a lot of methods so you can do a lot with one "copy". Check it out!

Return to “Ask For Help”

Who is online

Users browsing this forum: barbaque, barbudo2005, colt, Getfree, Google [Bot], vsub and 167 guests