haxestencyl

Cannot access function in Static Method / stackoverflow errors - Haxe


First of, here is a little bit of a background story. I am using the Game Engine Stencyl (the interface can be compared to Scratch) to teach basic gamedevelopment with. Unfortunately, since this is a rather small team, I am still missing a couple of useful build in functions, thus I decided to create my own extensions for it. I know my way around C#, Java and UnityScript, but these extensions will have to be written in Haxe. I've already tried a couple of days of finding my answers on their API page, but that is way beyond my level of experience.

The first issue is that I am simply trying to use a couple of map functions, but the methods are all static. Everytime I try to use a function like mapCount() in line 16, it will throw me an error saying: Cannot access controls in static function. So far I have managed to figure out that this is because I am not able to call non-static functions from a static method, but I have no idea how to tackle this (and probably more issues like this in the future).

The second issue is that when I un-comment line 14, and comment out line 16, the game will compile just fine, but will crash with an stackoverflow error. The arguments for this function are: createRecycledActor(actorType, x, y, layerPosition)

Here is the current state of my script, not doing a lot right now, but I'm taking babysteps to learn my way around this new language. If you require any more info, just let me know!

Ps, the trace function in line 15 works fine btw.

import com.stencyl.behavior.Script;
import com.stencyl.behavior.Script.*;
import com.stencyl.utils.Utils;

import com.stencyl.models.Actor;
import com.stencyl.models.actor.ActorType;

class MobileGameKit
{
    public var controls:Map<String,Actor> = new Map();

    public static function CreateThumbstick(mActorType:ActorType, mLocation:Int, mDirectionLock:Int)
    {
        //createRecycledActor(mActorType, 0, 0, Script.FRONT);
        trace("created thumbstick at position: "+mLocation+" with directionlock: "+mDirectionLock);
        trace("items in control map: " + Utils.mapCount(controls));
    }
}

Solution

  • Because controls is a member variable. i.e. each class instance has its own controls. While a static function is a function at class level. i.e. each class (among all instances) has only one copy of the function.

    So in a static function, you cannot access member variables because it won't be able to know from which instance to look for that member.

    To solve your problem, either make controls a static var, or pass the member controls as a parameter to your static function.

    btw, the language has been officially named as Haxe (instead haXe) for years already.