0

I am trying to use an instance variable as a parameter value in a method, but it is giving me an error. "Parameter initializer is unknown or is not a compile-time constant"

I want to use a non-constant instance variable though, and I assume there has to be some way around this besides calling this method from another method. Here is the code I'm referring to:

public function attack(target:Fighter=this.target):void {

}
1
  • 2
    You can't use this.target as an argument. Arguments are values come from outside the scope of your class. You have multiple options. For example, you can do this: public function attack(target:Fighter):void { if(target == null) target = this.target; } or you can only attack if a target has been previously set(maybe using a public function setTarget(newTarget:Target):void, and so on. Hard to tell what would be the best solution without knowing more about your game Commented Jan 18, 2014 at 23:19

2 Answers 2

2

What about:

public function attack(target:Fighter):void
{
    if(target == null)
        target = this.target;
}

and to be honest maybe it's easier to name one of variables _target to avoid confusion. You can use target = _target; instead of this..

Sign up to request clarification or add additional context in comments.

Comments

1

You cannot set an optional parameter that way. You can set optional parameters to a default value but not a reference. In this case if you want to keep it optional you could do something like this (or what @George Profenza suggested):

public function attack(target:Fighter=null):void {
    target = target ? target : this.target;
}

I see that you marked a correct answer already, but I'll explain that since you are defaulting any null parameters to this.target you would benefit from using this solution so you don't have to pass null each time you call attack() i.e. - you can do attack() instead of attack(null).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.