executing as3 code from a string

别来无恙 提交于 2021-01-29 02:43:37

问题


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?


回答1:


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
    }
}



回答2:


I am not sure I understand how you want to architect this idea.

If you want to use something similar to eval, there is no native way of doing this. Although, you can check this library and see and example here

Now, I would not recommend to use such thing for many reasons. Think about it a bit more, and you will figure out some by yourself.

I would suggest to implement a simple parser and load commands from your xml, then just interpret the data provided and execute the correspondent command:

<command id="hurt" params="-15"/>


来源:https://stackoverflow.com/questions/5513048/executing-as3-code-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!