Search code examples
javascriptflashportinghaxestatic-initialization

haxe uninitialized member variable inconsistent across platforms


I'm trying to cross compile an existing flash app written in haxe into javascript using openfl and haxe.

Under flash I can do the following:

class foo
{
    var bar : Int;

    public function new()
    {
        trace(bar); //under flash prints 0, under javascript undefined
    }
}

When compiling to javascript instead of 0, i get Undefined.

My questions is can I either make the compile print warnings/error if a member variable is left uninitialized by the constructor.

Even better can I make haxe I make it so haxe will initialize them for me in js to 0.

Same story with Bool = false, Float = 0 etc, I haven't tested but probably with Object = null also.

The app has 144 classes, and over 20k lines of code. Finding and adding explicit initializers manually will take a ton of time, which is why I'm looking for alternatives.


Solution

  • In case some one else has this question. I solved the issue by using sed and a regular expression to find and replace all uninitialized variables in my source tree.

    From the root of the source tree I ran the following commands under ubuntu.

    find . -print0 -name "*.hx" | xargs -0 -n1 sed -i -e "s/\(var [^:]\+:\s*Int\s*\);/\1 = 0;/g"
    find . -print0 -name "*.hx" | xargs -0 -n1 sed -i -e "s/\(var [^:]\+:\s*UInt\s*\);/\1 = 0;/g"
    find . -print0 -name "*.hx" | xargs -0 -n1 sed -i -e "s/\(var [^:]\+:\s*Bool\s*\);/\1 = false;/g"
    find . -print0 -name "*.hx" | xargs -0 -n1 sed -i -e "s/\(var [^:]\+:\s*Float\s*\);/\1 = 0;/g"
    find . -print0 -name "*.hx" | xargs -0 -n1 sed -i -e "s/\(var [^:]\+:\s*[^=]\+\s*\);/\1 = null;/g"
    

    That will replace

    var [variableName] : Int;  
    

    with

    var [variableName] : Int = 0;
    

    Similar for UInt, Bool, Float. All other types are set to null.

    I didn't write one for var [varName]; since there were only 4 instances of that in my source tree.