#Setting self-referential custom functions on a struct?

1 messages · Page 1 of 1 (latest)

hushed trout
#

Let's say I have a constructed struct with a non-static function that I then change from outside that struct. How can I think refer to variables or functions in the struct? I've tried both of the following without success:

hexGrid.GetMoveCost = function(_coords){
    return Get(_coords);
}
hexGrid.GetMoveCost = function(_coords){
    return self.Get(_coords);
}
hushed trout
#

In both cases, I get an error akin to:

#
Variable <unknown_object>.Get(100050, -2147483648) not set before reading it.
 at gml_Script_anon@442@gml_Object_ObjHexGridTest_Create_0 (line 20) -     return self.Get(_coords);```
gusty coral
#

So you need to do

#
hexGrid.GetMoveCost = method(hexGrid, function(_coords){
    return Get(_coords);
});
lilac horizon
#

A with statement would also do it I believe

gusty coral
#

It would yes

#

Since it’ll be changing the current scope

hushed trout
gusty coral
#
with(hexGrid) {
    GetMoveCost = function(_coords) {
        return Get(_coords);
    }
}
gusty coral
hushed trout
#

I'm aware, I was just mentioning a third method I discoverd that seems to work in at least this specific case.

gusty coral
#

Well the third case is still bounded to the current scope (not hexGrid)

#

You just happen to have a variable called hexGrid that you can access, from the same current scope

hushed trout
#

Ok, but I'm trying to understand if there's some functional difference that might bite me in the ass later.

gusty coral
#

Technically not really, unless you change hexGrid to something else, but still keep a reference of said hexGrid elsewhere

hushed trout
#

I think maybe the cleanest way is just using the with method... seems the most straightforward in terms of methodology as its just a scope change.

gusty coral
#
hexGrid.GetMoveCost = function(_coords){
    return hexGrid.Get(_coords);
}

hexGrids = [hexGrid];
hexGrid = undefined;
hexGrids[0].GetMoveCost(some_coord); // Error since it tries to access hexGrid, that’s now undefined
hushed trout
#

method is something I've never seen before, and will have to read up on

hushed trout
gusty coral
#

When you do

func = function() {}
#

It’s actually doing

func = method(self, function() {});
#

Hence methods

#

Or functions with a bound scope

#

Whenever you pass func to someone else, and they call it, the current scope will be the scope that was used at the time of creating the method