Conditional includes in ActionScript 3.0

This morning I have looked for a way to include another .as file depending on a variable. ActionScript 3’s include does not allow you to use variables, as it only accepts string literals.

The reasoning for this is that include is fired on compile time, so any variables are not set, determined, or even defined yet.

The Solution

Reading an article, I came across the solution — Config Constants. These are defined in your ActionScript 3.0 settings (File > ActionScript Settings > Config Constants ). Here you can define compile-time constants, and have functionality depend on them.

config_constants

In my example, I was creating an application that had different text for different products. my .as files were bringing in the text in the form of an array.

The true/false Config Constant

In this example, you can use your constant as an if statement.

CONFIG::PRODUCT_IS_BLUE {
     // true
     include "data/product_blue.as";
} else {
     // false
     include "data/product.as";
}

The Config Constant Switch Case

In this example, I defined my constant as a string value, not a boolean.

switch( CONFIG::PRODUCT_NAME ) {
     case 'blueProduct':
          include "data/product_blue.as";
          break;
     case 'redProduct':
          include "data/product_red.as";
          break;
     default:
          include "data/product.as":
}

Leave your comments below!

Leave a Reply

Your email address will not be published. Required fields are marked *