actionscript-3flashactionscriptcs3

How to refer to existing variable(s) without creating a new one?


I have no idea how to ask this question.

I have a variable

public static var MaxDurabilityTestItem:Number = 3;

I have a function

    public static function setItemInSlot(Item:String, Slot:Number, MaxDurability:Number = 0)
    {
        UI_Taskbar_Inventory.InventoryItems[Slot] = Item;

        if(MaxDurability == 0)
        {
            trace("Before change " + UI_Taskbar_Inventory.InventoryDurability);
            UI_Taskbar_Inventory.InventoryDurability[Slot] = "MaxDurability" + Item;
            trace("After change " + UI_Taskbar_Inventory.InventoryDurability);
        }
        else
        {
            trace("not using default durability");
        }
    }

The only part of this function that is causing me headaches is this line

UI_Taskbar_Inventory.InventoryDurability[Slot] = "MaxDurability" + Item

It outputs

Before change 0,0,0,0,0,0,0,0

After change 0,MaxDurabilityTestItem,0,0,0,0,0,0

While I want it to output

Before change 0,0,0,0,0,0,0,0

After change 0,3,0,0,0,0,0,0

I know the issue, however, I don't know how to fix it. "MaxDurability" + Item makes a string called MaxDurabilityTestItem, rather than referring to my variable MaxDurabilityTestItem.

How can I change this so that it refers to my variable MaxDurabilityTestItem, rather than this string it creates?


Solution

  • "MaxDurability" + Item makes a string called MaxDurabilityTestItem,

    Because you automatically defined a "string" by using the quotes. I can only assume Item is also string with text "TestItem". So you've simply joined+two+strings together.

    (2)

    ...rather than referring to my variable MaxDurabilityTestItem.

    Try as:

    UI_Taskbar_Inventory.InventoryDurability[Slot] = MaxDurabilityTestItem; //now using your defined variable
    

    Edit :

    Just in case you really want to use a string as reference to the variable itself :

    Use this[ "name of some var" ]... where this will target the current class and ["name"] will find such specified variable within the current class.

    Try:

    if(MaxDurability == 0)
    {
        trace("Before change " + UI_Taskbar_Inventory.InventoryDurability);
        UI_Taskbar_Inventory.InventoryDurability[Slot] = this[ "MaxDurability" + Item ];
        trace("After change " + UI_Taskbar_Inventory.InventoryDurability);
    }
    else
    { trace("not using default durability"); }