public override DynValue Eval(ScriptExecutionContext context) { DynValue v1 = m_Exp1.Eval(context).ToScalar(); DynValue v2 = m_Exp1.Eval(context).ToScalar(); double?d1 = v1.CastToNumber(); double?d2 = v1.CastToNumber(); if (d1.HasValue && d2.HasValue) { return(DynValue.NewNumber(Math.Pow(d1.Value, d2.Value))); } throw new DynamicExpressionException("Attempt to perform arithmetic on non-numbers."); }
internal IList <int> GetResultList() { if (_result.Type == DataType.Number) { var dbl = _result.CastToNumber(); return((dbl == null) ? new List <int>() : new List <int> { (int)dbl }); } if (_result.Type == DataType.Table) { return(_result.Table.Values.Select(v => (int)v.CastToNumber()).ToList()); } return(new List <int>()); }
public override DynValue Eval(ScriptExecutionContext context) { DynValue v = m_Exp.Eval(context).ToScalar(); switch (m_OpText) { case "not": return(DynValue.NewBoolean(!v.CastToBool())); case "#": return(v.GetLength()); case "-": { Fix?d = v.CastToNumber(); if (d.HasValue) { return(DynValue.NewNumber(-d.Value)); } throw new DynamicExpressionException("Attempt to perform arithmetic on non-numbers."); } default: throw new DynamicExpressionException("Unexpected unary operator '{0}'", m_OpText); } }
private int ExecMul(Instruction i, int instructionPtr) { DynValue r = m_ValueStack.Pop().ToScalar(); DynValue l = m_ValueStack.Pop().ToScalar(); double?rn = r.CastToNumber(); double?ln = l.CastToNumber(); if (ln.HasValue && rn.HasValue) { m_ValueStack.Push(DynValue.NewNumber(ln.Value * rn.Value)); return(instructionPtr); } else { int ip = Internal_InvokeBinaryMetaMethod(l, r, "__mul", instructionPtr); if (ip >= 0) { return(ip); } else { throw ScriptRuntimeException.ArithmeticOnNonNumber(l, r); } } }
private int ExecMod(Instruction i, int instructionPtr) { DynValue r = m_ValueStack.Pop().ToScalar(); DynValue l = m_ValueStack.Pop().ToScalar(); double?rn = r.CastToNumber(); double?ln = l.CastToNumber(); if (ln.HasValue && rn.HasValue) { double mod = Math.IEEERemainder(ln.Value, rn.Value); if (mod < 0) { mod += rn.Value; } m_ValueStack.Push(DynValue.NewNumber(mod)); return(instructionPtr); } else { int ip = Internal_InvokeBinaryMetaMethod(l, r, "__div", instructionPtr); if (ip >= 0) { return(ip); } else { throw ScriptRuntimeException.ArithmeticOnNonNumber(l, r); } } }
public static DynValue @char(ScriptExecutionContext executionContext, CallbackArguments args) { StringBuilder sb = new StringBuilder(args.Count); for (int i = 0; i < args.Count; i++) { DynValue v = args[i]; double d = 0d; if (v.Type == DataType.String) { double?nd = v.CastToNumber(); if (nd == null) { args.AsType(i, "char", DataType.Number, false); } else { d = nd.Value; } } else { args.AsType(i, "char", DataType.Number, false); d = v.Number; } sb.Append((char)(d)); } return(DynValue.NewString(sb.ToString())); }
public void Test_CallFunction_InputInts_ReturnSum() { // Test passing more than one input functions.LoadScript(testCode1, "testCode1"); DynValue value = functions.Call("test_func3", 4, 7); Assert.AreEqual(11, (int)value.CastToNumber()); }
/// <summary> /// Set overlay to display perototype with name "name". /// </summary> /// <param name="name">Name of overlay prototype.</param> public void SetOverlay(string name) { if (name == "None") { meshRenderer.enabled = false; currentOverlay = name; HideGUITooltip(); return; } else if (PrototypeManager.Overlay.Has(name)) { meshRenderer.enabled = true; currentOverlay = name; OverlayDescriptor descr = PrototypeManager.Overlay.Get(name); if (FunctionsManager.Overlay.HasFunction(descr.LuaFunctionName) == false) { UnityDebugger.Debugger.LogError("OverlayMap", string.Format("Couldn't find a function named '{0}' in Overlay functions", descr.LuaFunctionName)); return; } bool loggedOnce = false; valueAt = (x, y, z) => { if (WorldController.Instance == null) { return(0); } Tile tile = WorldController.Instance.GetTileAtWorldCoord(new Vector3(x, y, z)); DynValue result = FunctionsManager.Overlay.Call(descr.LuaFunctionName, new object[] { tile, World.Current }); double? value = result.CastToNumber(); if (value == null) { if (loggedOnce == false) { UnityDebugger.Debugger.LogError("OverlayMap", string.Format("The return value from the function named '{0}' was null for tile at ({1}, {2}, {3})", descr.LuaFunctionName, x, y, z)); loggedOnce = true; } return(0); } return((int)value); }; ColorMapSG = descr.ColorMap; Bake(); ShowGUITooltip(); } else { UnityDebugger.Debugger.LogWarning("OverlayMap", string.Format("Overlay with name {0} not found in prototypes", name)); } }
private static int?GetTimeTableField(Table t, string key) { DynValue v = t.Get(key); double? d = v.CastToNumber(); if (d.HasValue) { return((int)d.Value); } return(null); }
private DynValue Place(ScriptExecutionContext _context, CallbackArguments _args) { // get the argument DynValue argument = _args.RawGet(0, true); // cast to number int type = (int)argument.CastToNumber(); // call the place func m_builder.Place((PrimitiveType)type); return(DynValue.Void); }
public static object NumberToByte(DynValue v) { double?n = v.CastToNumber(); if (!n.HasValue) { throw ScriptRuntimeException.ConvertToNumberFailed(0); } if (n.Value < 0 || n.Value > 255) { throw new ScriptRuntimeException(string.Format("number is out of range (0-255)")); } return((byte)n.Value); }
private double EvalArithmetic(DynValue v1, DynValue v2) { var nd1 = v1.CastToNumber(); var nd2 = v2.CastToNumber(); if (nd1 == null || nd2 == null) { throw new DynamicExpressionException("Attempt to perform arithmetic on non-numbers."); } double d1 = nd1.Value; double d2 = nd2.Value; switch (m_Operator) { case Operator.Add: return(d1 + d2); case Operator.Sub: return(d1 - d2); case Operator.Mul: return(d1 * d2); case Operator.Div: return(d1 / d2); case Operator.Mod: { double mod = Math.IEEERemainder(d1, d2); if (mod < 0) { mod += d2; } return(mod); } default: throw new DynamicExpressionException("Unsupported operator {0}", m_Operator); } }
private Fix EvalArithmetic(DynValue v1, DynValue v2) { Fix?nd1 = v1.CastToNumber(); Fix?nd2 = v2.CastToNumber(); if (nd1 == null || nd2 == null) { throw new DynamicExpressionException("Attempt to perform arithmetic on non-numbers."); } Fix d1 = nd1.Value; Fix d2 = nd2.Value; switch (m_Operator) { case Operator.Add: return(d1 + d2); case Operator.Sub: return(d1 - d2); case Operator.Mul: return(d1 * d2); case Operator.Div: return(d1 / d2); case Operator.Mod: { Fix mod = d1 % d2; if (mod < 0) { mod += d2; } return(mod); } default: throw new DynamicExpressionException("Unsupported operator {0}", m_Operator); } }
private static int GetTableLength(ScriptExecutionContext executionContext, DynValue vlist) { DynValue __len = executionContext.GetMetamethod(vlist, "__len"); if (__len.IsNotNil()) { DynValue lenv = executionContext.GetScript().Call(__len, vlist); double?len = lenv.CastToNumber(); if (len == null) { throw new ScriptRuntimeException("object length is not a number"); } return((int)len); } else { return((int)vlist.Table.Length); } }
private double EvalArithmetic(DynValue v1, DynValue v2, bool t1Neg = false) { double?nd1 = v1.CastToNumber(); double?nd2 = v2.CastToNumber(); if (nd1 == null || nd2 == null) { throw new DynamicExpressionException("Attempt to perform arithmetic on non-numbers."); } double d1 = nd1.Value; double d2 = nd2.Value; switch (m_Operator) { case Operator.Add: return(d1 + d2); case Operator.Sub: return(d1 - d2); case Operator.Mul: return(d1 * d2); case Operator.Div: return(d1 / d2); case Operator.Mod: return((d1) - Math.Floor((d1) / (d2)) * (d2)); case Operator.Power: var res = Math.Pow(t1Neg ? -d1 : d1, d2); return(t1Neg ? -res : res); default: throw new DynamicExpressionException("Unsupported operator {0}", m_Operator); } }
private int ExecNeg(Instruction i, int instructionPtr) { DynValue r = m_ValueStack.Pop().ToScalar(); double? rn = r.CastToNumber(); if (rn.HasValue) { m_ValueStack.Push(DynValue.NewNumber(-rn.Value)); return(instructionPtr); } else { int ip = Internal_InvokeUnaryMetaMethod(r, "__unm", instructionPtr); if (ip >= 0) { return(ip); } else { throw ScriptRuntimeException.ArithmeticOnNonNumber(r); } } }
private double EvalArithmetic(DynValue v1, DynValue v2) { double? nd1 = v1.CastToNumber(); double? nd2 = v2.CastToNumber(); if (nd1 == null || nd2 == null) throw new DynamicExpressionException("Attempt to perform arithmetic on non-numbers."); double d1 = nd1.Value; double d2 = nd2.Value; switch (m_Operator) { case Operator.Add: return d1 + d2; case Operator.Sub: return d1 - d2; case Operator.Mul: return d1 * d2; case Operator.Div: return d1 / d2; case Operator.Mod: { double mod = Math.IEEERemainder(d1, d2); if (mod < 0) mod += d2; return mod; } default: throw new DynamicExpressionException("Unsupported operator {0}", m_Operator); } }
public static DynValue tonumber(ScriptExecutionContext executionContext, CallbackArguments args) { if (args.Count < 1) { throw ScriptRuntimeException.BadArgumentValueExpected(0, "tonumber"); } DynValue e = args[0]; DynValue b = args.AsType(1, "tonumber", DataType.Number, true); if (b.IsNil()) { if (e.Type == DataType.Number) { return(e); } if (e.Type != DataType.String) { return(DynValue.Nil); } double?res = e.CastToNumber(); if (res != null) { return(DynValue.NewNumber(res.Value)); } return(DynValue.Nil); } else { DynValue ee; if (args[0].Type != DataType.Number) { ee = args.AsType(0, "tonumber", DataType.String, false); } else { ee = DynValue.NewString(args[0].Number.ToString(CultureInfo.InvariantCulture)); }; if (ee.String.Length < 0) { return(DynValue.Nil); } int bb = (int)b.Number; double uiv = 0; var trimmed = ee.String.Trim(); if (trimmed.Length == 0) { return(DynValue.Nil); } bool negate = false; int startIdx = 0; if (trimmed[0] == '-') { negate = true; startIdx = 1; } if (trimmed[0] == '+') { startIdx = 1; } if (bb <= 36 && bb > 1) { for (int ij = startIdx; ij < trimmed.Length; ij++) { char ch = trimmed[ij]; int value; if (ch >= 97) { value = ch - 87; } else if (ch >= 65) { value = ch - 55; } else { value = ch - 48; } if (value < 0 || value >= bb) { return(DynValue.Nil); } uiv = uiv * bb + value; } } else { throw new ScriptRuntimeException("bad argument #2 to 'tonumber' (base out of range)"); } return(DynValue.NewNumber(negate ? -uiv : uiv)); } }
public static Table AskForParametersNoClear() { // TODO add repeating with previous parameters // FIXME check for duplicate keys if (ScriptContext.context.ui_parameters.keys == null || ScriptContext.context.ui_parameters.keys.Count <= 0) { ScriptContext.context.Warn("AskForParameters called with no parameters set up."); return(null); } Dictionary <string, string> dict = ScriptMode.RequestAndWaitForParams(); if (dict == null) { // FIXME do this without an error message probably? throw new ScriptRuntimeException("User cancelled script execution."); } Table output = new Table(ScriptContext.context.script); foreach (KeyValuePair <string, string> pair in dict) { output.Set( pair.Key, DynValue.FromObject(ScriptContext.context.script, pair.Value) ); } int count = ScriptContext.context.ui_parameters.datatypes.Count; if (ScriptContext.context.ui_parameters.keys.Count != count) { Logger.WriteLogLine("Inconsistent parameter counts in Lua script!"); Logger.WriteLogLine("datatypes: "); foreach (DataType o in ScriptContext.context.ui_parameters.datatypes) { Logger.WriteLogLine(o.ToString()); } Logger.WriteLogLine("keys: "); foreach (string o in ScriptContext.context.ui_parameters.keys) { if (o == null) { Logger.WriteLogLine("null"); } else { Logger.WriteLogLine(o); } } Logger.WriteLogLine("labels: "); foreach (string o in ScriptContext.context.ui_parameters.labels) { if (o == null) { Logger.WriteLogLine("null"); } else { Logger.WriteLogLine(o); } } Logger.WriteLogLine("labels: "); foreach (string o in ScriptContext.context.ui_parameters.defaultvalues) { if (o == null) { Logger.WriteLogLine("null"); } else { Logger.WriteLogLine(o); } } throw new ScriptRuntimeException("Inconsistent parameter counts in Lua script, might be a DBXLua bug. :("); } for (int i = 0; i < count; i++) { DataType cur_type = ScriptContext.context.ui_parameters.datatypes[i]; DynValue cur_value = output.Get(ScriptContext.context.ui_parameters.keys[i]); switch (cur_type) { case DataType.Boolean: cur_value.Assign(DynValue.NewBoolean(cur_value.CastToBool())); //output.Set(ScriptContext.context.ui_parameters.keys[i], cur_value.CastToBool()); break; case DataType.Number: double d = cur_value.CastToNumber() ?? 0; cur_value.Assign(DynValue.NewNumber(d)); break; default: break; // nope } } return(output); }
public static DynValue traceback(ScriptExecutionContext executionContext, CallbackArguments args) { StringBuilder sb = new StringBuilder(); DynValue vmessage = args[0]; DynValue vlevel = args[1]; double defaultSkip = 1.0; Coroutine cor = executionContext.GetCallingCoroutine(); if (vmessage.Type == DataType.Thread) { cor = vmessage.Coroutine; vmessage = args[1]; vlevel = args[2]; defaultSkip = 0.0; } if (vmessage.IsNotNil() && vmessage.Type != DataType.String && vmessage.Type != DataType.Number) { return(vmessage); } string message = vmessage.CastToString(); int skip = (int)((vlevel.CastToNumber()) ?? defaultSkip); WatchItem[] stacktrace = cor.GetStackTrace(Math.Max(0, skip)); if (message != null) { sb.AppendLine(message); } sb.AppendLine("stack traceback:"); foreach (WatchItem wi in stacktrace) { string name; if (wi.Name == null) { if (wi.RetAddress < 0) { name = "main chunk"; } else { name = "?"; } } else { name = "function '" + wi.Name + "'"; } string loc = wi.Location != null?wi.Location.FormatLocation(executionContext.GetScript()) : "[clr]"; sb.AppendFormat("\t{0}: in {1}\n", loc, name); } return(DynValue.NewString(sb)); }