Search code examples
xmlactionscript-3stringexecute

executing as3 code from a string


I'm working on a simple text rpg and I'm storing all of my data objects out as xml files but I need to be able to run some simple statements for many things.

I have done some googling I havent come up with much.

What I'm trying to do is take simple statements like:

playerhp += 15;

or

if(playerisvampire == 1) {blah blah;}

and embed them inside of the xml structure so that an item or conversation line can contain the checks and executable code leaving the rpg class as more of an interpreter and interface. Is such a thing possible?


Solution

  • ActionScript 3 contains no eval function anymore, so this is not possible directly. However, you can roll your own simple interpreter to do this manually. Something like this:

    var item:XML =
        <health_item>
            <action name="hp_change" value="15"/>
        </health_item>;
    

    Check action name in ActionScript, find corresponding function and call it with "value" argument:

    for each (var action:XML in item.action) {
        var actionName:String = action.@name;
    
        //switch variant
        switch (actionName) {
            case "hp_change":
                hpChange(action.@value);
                break;
            //and so on for other known actions
        }
    
        //direct call by name variant
        if (hasOwnProperty(actionName)) {
            this[actionName](action.@value);
        } else {
             //report error
        }
    }