private static EvalValue CalcFunction(FuncEnvironment env, AstFunction ast) { // 初始化实参 var callee = env.GetMainEnv().GetFuncDef(ast.token.GetText()); if (callee != null) { // 脚本方法 var paramList = callee.paramList; for (var i = 0; i < paramList.length; ++i) { var item = paramList.GetName(i); if (ast.args.ChildrenCount() <= i) { throw new RunTimeException("实参不足", ast); } var argItem = ast.args.ChildAt(i) as AstExpression; env.AddArg(item, argItem.Eval(env.parent)); } // 执行函数体 var funcBody = callee.block; var ret = new EvalValue(); foreach (var item in funcBody) { try { ret = item.Eval(env); } catch (ReturnException) { break; } } if (env.Get("return@" + env.GetScopeName()) != null) { return(env.Get("return@" + env.GetScopeName())); } return(ret); } else { var csm = env.GetMainEnv().GetCsFuncDef(ast.token.GetText()); if (csm != null) { // CS方法 var csRet = csm(ast.args.ToArgArray(env)); var ret = new EvalValue(csRet); return(ret); } } throw new RunTimeException("函数未定义:" + ast.token.GetText() + "()", ast); }
public static EvalValue CallFunc(FuncEnvironment env, AstFuncDef callee, params object[] args) { var paramList = callee.paramList; if (args.Length < paramList.length) { throw new RunTimeException(string.Format("实参不足: 需要{0}个,提供了{0}个", paramList.length, args.Length)); } for (var i = 0; i < paramList.length; ++i) { var item = paramList.GetName(i); var argItem = args[i]; if (argItem is System.Int32) { env.AddArg(item, new EvalValue((int)argItem)); } else if (argItem is System.String) { env.AddArg(item, new EvalValue(argItem as System.String)); } else { throw new RunTimeException("参数类型不正确:" + argItem.GetType().ToString()); } } // 执行函数体 var funcBody = callee.block; var ret = new EvalValue(); foreach (var item in funcBody) { try { ret = item.Eval(env); } catch (ReturnException) { break; } } if (env.Get("return@" + env.GetScopeName()) != null) { return(env.Get("return@" + env.GetScopeName())); } return(ret); }
/// <summary> /// Csharp调用脚本函数 /// </summary> /// <param name="name"></param> /// <returns></returns> public RunResult CallScriptFunction(string name, params object[] args) { var func = GetFuncDef(name); var ret = new RunResult(); var mainEnv = new MainEnvironment(this); var funcEnv = new FuncEnvironment(mainEnv, Utils.GetScopeString()); try { ret.returnVal = Evaluator.CallFunc(funcEnv, func, args).ToString(); ret.success = true; } catch (RunTimeException e) { ret.error = "运行时错误:" + e.Message; } catch (Exception e) { ret.error = string.Format("其他错误[{0}]-{1}", e.GetType().ToString(), e.Message); } Utils.LogDebug("脚本函数执行完毕:" + ret.ToString()); return(ret); }