public static DynValue @char(ScriptExecutionContext executionContext, CallbackArguments args) { var sb = new StringBuilder(args.Count); for (var i = 0; i < args.Count; i++) { var v = args[i]; var d = 0d; if (v.Type == DataType.String) { var 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 static DynValue type(ScriptExecutionContext executionContext, CallbackArguments args) { if (args.Count < 1) throw ScriptRuntimeException.BadArgumentValueExpected(0, "type"); DynValue v = args[0]; return DynValue.NewString(v.Type.ToLuaTypeString()); }
public static DynValue setuservalue(ScriptExecutionContext executionContext, CallbackArguments args) { var v = args.AsType(0, "setuservalue", DataType.UserData, false); var t = args.AsType(0, "setuservalue", DataType.Table, true); return v.UserData.UserValue = t; }
public static DynValue execute(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue v = args.AsType(0, "execute", DataType.String, true); if (v.IsNil()) { return DynValue.NewBoolean(true); } else { try { int exitCode = Script.GlobalOptions.Platform.OS_Execute(v.String); return DynValue.NewTuple( DynValue.Nil, DynValue.NewString("exit"), DynValue.NewNumber(exitCode)); } catch (Exception) { // +++ bad to swallow.. return DynValue.Nil; } } }
public static DynValue sort(ScriptExecutionContext executionContext, CallbackArguments args) { var vlist = args.AsType(0, "sort", DataType.Table, false); var lt = args[1]; if (lt.Type != DataType.Function && lt.Type != DataType.ClrFunction && lt.IsNotNil()) args.AsType(1, "sort", DataType.Function, true); // this throws var end = GetTableLength(executionContext, vlist); var values = new List<DynValue>(); for (var i = 1; i <= end; i++) values.Add(vlist.Table.Get(i)); try { values.Sort((a, b) => SortComparer(executionContext, a, b, lt)); } catch (InvalidOperationException ex) { if (ex.InnerException is ScriptRuntimeException) throw ex.InnerException; } for (var i = 0; i < values.Count; i++) { vlist.Table.Set(i + 1, values[i]); } return vlist; }
public static DynValue rawget(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue table = args.AsType(0, "rawget", DataType.Table); DynValue index = args[1]; return table.Table.Get(index); }
private static DynValue SetErrorHandlerStrategy(string funcName, ScriptExecutionContext executionContext, CallbackArguments args, DynValue handlerBeforeUnwind) { var v = args[0]; var a = new DynValue[args.Count - 1]; for (var i = 1; i < args.Count; i++) a[i - 1] = args[i]; if (args[0].Type == DataType.ClrFunction) { try { var ret = args[0].Callback.Invoke(executionContext, a); if (ret.Type == DataType.TailCallRequest) { if (ret.TailCallData.Continuation != null || ret.TailCallData.ErrorHandler != null) throw new ScriptRuntimeException( "the function passed to {0} cannot be called directly by {0}. wrap in a script function instead.", funcName); return DynValue.NewTailCallReq(new TailCallData { Args = ret.TailCallData.Args, Function = ret.TailCallData.Function, Continuation = new CallbackFunction(pcall_continuation, funcName), ErrorHandler = new CallbackFunction(pcall_onerror, funcName), ErrorHandlerBeforeUnwind = handlerBeforeUnwind }); } if (ret.Type == DataType.YieldRequest) { throw new ScriptRuntimeException( "the function passed to {0} cannot be called directly by {0}. wrap in a script function instead.", funcName); } return DynValue.NewTupleNested(DynValue.True, ret); } catch (ScriptRuntimeException ex) { executionContext.PerformMessageDecorationBeforeUnwind(handlerBeforeUnwind, ex); return DynValue.NewTupleNested(DynValue.False, DynValue.NewString(ex.DecoratedMessage)); } } if (args[0].Type != DataType.Function) { return DynValue.NewTupleNested(DynValue.False, DynValue.NewString("attempt to " + funcName + " a non-function")); } return DynValue.NewTailCallReq(new TailCallData { Args = a, Function = v, Continuation = new CallbackFunction(pcall_continuation, funcName), ErrorHandler = new CallbackFunction(pcall_onerror, funcName), ErrorHandlerBeforeUnwind = handlerBeforeUnwind }); }
public static DynValue eval(ScriptExecutionContext executionContext, CallbackArguments args) { try { if (args[0].Type == DataType.UserData) { UserData ud = args[0].UserData; if (ud.Object is DynamicExprWrapper) { return ((DynamicExprWrapper)ud.Object).Expr.Evaluate(executionContext); } else { throw ScriptRuntimeException.BadArgument(0, "dynamic.eval", "A userdata was passed, but was not a previously prepared expression."); } } else { DynValue vs = args.AsType(0, "dynamic.eval", DataType.String, false); DynamicExpression expr = executionContext.GetScript().CreateDynamicExpression(vs.String); return expr.Evaluate(executionContext); } } catch (SyntaxErrorException ex) { throw new ScriptRuntimeException(ex); } }
public static DynValue debug(ScriptExecutionContext executionContext, CallbackArguments args) { var script = executionContext.GetScript(); if (script.Options.DebugInput == null) throw new ScriptRuntimeException("debug.debug not supported on this platform/configuration"); var interpreter = new ReplInterpreter(script) { HandleDynamicExprs = false, HandleClassicExprsSyntax = true }; while (true) { var s = script.Options.DebugInput(interpreter.ClassicPrompt + " "); try { var result = interpreter.Evaluate(s); if (result != null && result.Type != DataType.Void) script.Options.DebugPrint(string.Format("{0}", result)); } catch (InterpreterException ex) { script.Options.DebugPrint(string.Format("{0}", ex.DecoratedMessage ?? ex.Message)); } catch (Exception ex) { script.Options.DebugPrint(string.Format("{0}", ex.Message)); } } }
public static DynValue create(ScriptExecutionContext executionContext, CallbackArguments args) { if (args[0].Type != DataType.Function && args[0].Type != DataType.ClrFunction) args.AsType(0, "create", DataType.Function); // this throws return executionContext.GetScript().CreateCoroutine(args[0]); }
private static DynValue exec2n(CallbackArguments args, string funcName, double defVal, Func<double, double, double> func) { DynValue arg = args.AsType(0, funcName, DataType.Number, false); DynValue arg2 = args.AsType(1, funcName, DataType.Number, true); return DynValue.NewNumber(func(arg.Number, arg2.IsNil() ? defVal : arg2.Number)); }
public static DynValue pairs(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue table = args[0]; DynValue meta = executionContext.GetMetamethodTailCall(table, "__pairs", args.GetArray()); return meta ?? DynValue.NewTuple(DynValue.NewCallback(next), table); }
public static DynValue ipairs(ScriptExecutionContext executionContext, CallbackArguments args) { var table = args[0]; var meta = executionContext.GetMetamethodTailCall(table, "__ipairs", args.GetArray()); return meta ?? DynValue.NewTuple(DynValue.NewCallback(__next_i), table, DynValue.NewNumber(0)); }
private static int[] BuildArrayIndices(CallbackArguments args, int count) { int[] indices = new int[count]; for (int i = 0; i < count; i++) indices[i] = args.AsInt(i, "userdata_array_indexer"); return indices; }
public static DynValue @byte(ScriptExecutionContext executionContext, CallbackArguments args) { var vs = args.AsType(0, "byte", DataType.String, false); var vi = args.AsType(1, "byte", DataType.Number, true); var vj = args.AsType(2, "byte", DataType.Number, true); return PerformByteLike(vs, vi, vj, i => Unicode2Ascii(i)); }
public static DynValue getuservalue(ScriptExecutionContext executionContext, CallbackArguments args) { var v = args[0]; if (v.Type != DataType.UserData) return DynValue.Nil; return v.UserData.UserValue ?? DynValue.Nil; }
public static DynValue rawset(ScriptExecutionContext executionContext, CallbackArguments args) { var table = args.AsType(0, "rawset", DataType.Table); var index = args[1]; table.Table.Set(index, args[2]); return table; }
/// <summary> /// The internal callback which actually executes the method /// </summary> /// <param name="script">The script.</param> /// <param name="obj">The object.</param> /// <param name="context">The context.</param> /// <param name="args">The arguments.</param> /// <returns></returns> public override DynValue Execute(Script script, object obj, ScriptExecutionContext context, CallbackArguments args) { if (m_CallbackFunc != null) { var retv = m_CallbackFunc(obj, context, args); return ClrToScriptConversions.ObjectToDynValue(script, retv); } return DynValue.Void; }
public static DynValue getenv(ScriptExecutionContext executionContext, CallbackArguments args) { var varName = args.AsType(0, "getenv", DataType.String, false); var val = Script.GlobalOptions.Platform.GetEnvironmentVariable(varName.String); if (val == null) return DynValue.Nil; return DynValue.NewString(val); }
public static DynValue wrap(ScriptExecutionContext executionContext, CallbackArguments args) { if (args[0].Type != DataType.Function && args[0].Type != DataType.ClrFunction) args.AsType(0, "wrap", DataType.Function); // this throws DynValue v = create(executionContext, args); DynValue c = DynValue.NewCallback(__wrap_wrapper); c.Callback.AdditionalData = v; return c; }
internal LuaState(ScriptExecutionContext executionContext, CallbackArguments args, string functionName) { ExecutionContext = executionContext; m_Stack = new List<DynValue>(16); for (int i = 0; i < args.Count; i++) m_Stack.Add(args[i]); FunctionName = functionName; }
public static DynValue difftime(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue t2 = args.AsType(0, "difftime", DataType.Number, false); DynValue t1 = args.AsType(1, "difftime", DataType.Number, true); if (t1.IsNil()) return DynValue.NewNumber(t2.Number); return DynValue.NewNumber(t2.Number - t1.Number); }
public static DynValue next(ScriptExecutionContext executionContext, CallbackArguments args) { var table = args.AsType(0, "next", DataType.Table); var index = args[1]; var pair = table.Table.NextKey(index); if (pair.HasValue) return DynValue.NewTuple(pair.Value.Key, pair.Value.Value); throw new ScriptRuntimeException("invalid key to 'next'"); }
private static DynValue MakeReturnTuple(bool retstatus, CallbackArguments args) { DynValue[] rets = new DynValue[args.Count + 1]; for (int i = 0; i < args.Count; i++) rets[i + 1] = args[i]; rets[0] = DynValue.NewBoolean(retstatus); return DynValue.NewTuple(rets); }
public static DynValue getmetatable(ScriptExecutionContext executionContext, CallbackArguments args) { var v = args[0]; var S = executionContext.GetScript(); if (v.Type.CanHaveTypeMetatables()) return DynValue.NewTable(S.GetTypeMetatable(v.Type)); if (v.Type == DataType.Table) return DynValue.NewTable(v.Table.MetaTable); return DynValue.Nil; }
public static DynValue exit(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue v_exitCode = args.AsType(0, "exit", DataType.Number, true); int exitCode = 0; if (v_exitCode.IsNotNil()) exitCode = (int)v_exitCode.Number; Script.GlobalOptions.Platform.OS_ExitFast(exitCode); throw new InvalidOperationException("Unreachable code.. reached."); }
public static uint Bitwise(string funcName, CallbackArguments args, Func<uint, uint, uint> accumFunc) { uint accum = ToUInt32(args.AsType(0, funcName, DataType.Number, false)); for (int i = 1; i < args.Count; i++) { uint vv = ToUInt32(args.AsType(i, funcName, DataType.Number, false)); accum = accumFunc(accum, vv); } return accum; }
public static DynValue pack(ScriptExecutionContext executionContext, CallbackArguments args) { var t = new Table(executionContext.GetScript()); var v = DynValue.NewTable(t); for (var i = 0; i < args.Count; i++) t.Set(i + 1, args[i]); t.Set("n", DynValue.NewNumber(args.Count)); return v; }
public static DynValue time(ScriptExecutionContext executionContext, CallbackArguments args) { DateTime date = DateTime.UtcNow; if (args.Count > 0) { DynValue vt = args.AsType(0, "time", DataType.Table, true); if (vt.Type == DataType.Table) date = ParseTimeTable(vt.Table); } return GetUnixTime(date); }
private static DynValue __index_callback(ScriptExecutionContext executionContext, CallbackArguments args) { string name = args[1].CastToString(); if (name == "stdin") return GetStandardFile(executionContext.GetScript(), StandardFileType.StdIn); else if (name == "stdout") return GetStandardFile(executionContext.GetScript(), StandardFileType.StdOut); else if (name == "stderr") return GetStandardFile(executionContext.GetScript(), StandardFileType.StdErr); else return DynValue.Nil; }
public static DynValue yield(ScriptExecutionContext executionContext, CallbackArguments args) { return(DynValue.NewYieldReq(args.GetArray())); }
public static DynValue lshr(ScriptExecutionContext executionContext, CallbackArguments args) { return(exec2(args, "lshr", (x, y) => new Fix((int)((uint)x.Raw >> (int)y)))); }
public static DynValue cos(ScriptExecutionContext executionContext, CallbackArguments args) { return(exec1(args, "cos", (x) => FixMath.Cos(x * 360))); }
/// <summary> /// Performs the overloaded call. /// </summary> /// <param name="script">The script.</param> /// <param name="obj">The object.</param> /// <param name="context">The context.</param> /// <param name="args">The arguments.</param> /// <returns></returns> /// <exception cref="ScriptRuntimeException">function call doesn't match any overload</exception> private DynValue PerformOverloadedCall(Script script, object obj, ScriptExecutionContext context, CallbackArguments args) { bool extMethodCacheNotExpired = IgnoreExtensionMethods || (obj == null) || m_ExtensionMethodVersion == UserData.GetExtensionMethodsChangeVersion(); // common case, let's optimize for it if (m_Overloads.Count == 1 && m_ExtOverloads.Count == 0 && extMethodCacheNotExpired) { return(m_Overloads[0].Execute(script, obj, context, args)); } if (m_Unsorted) { m_Overloads.Sort(new OverloadableMemberDescriptorComparer()); m_Unsorted = false; } if (extMethodCacheNotExpired) { for (int i = 0; i < m_Cache.Length; i++) { if (m_Cache[i] != null && CheckMatch(obj != null, args, m_Cache[i])) { #if DEBUG_OVERLOAD_RESOLVER System.Diagnostics.Debug.WriteLine(string.Format("[OVERLOAD] : CACHED! slot {0}, hits: {1}", i, m_CacheHits)); #endif return(m_Cache[i].Method.Execute(script, obj, context, args)); } } } // resolve on overloads first int maxScore = 0; IOverloadableMemberDescriptor bestOverload = null; for (int i = 0; i < m_Overloads.Count; i++) { if (obj != null || m_Overloads[i].IsStatic) { int score = CalcScoreForOverload(context, args, m_Overloads[i], false); if (score > maxScore) { maxScore = score; bestOverload = m_Overloads[i]; } } } if (!IgnoreExtensionMethods && (obj != null)) { if (!extMethodCacheNotExpired) { m_ExtensionMethodVersion = UserData.GetExtensionMethodsChangeVersion(); m_ExtOverloads = UserData.GetExtensionMethodsByNameAndType(this.Name, this.DeclaringType); } for (int i = 0; i < m_ExtOverloads.Count; i++) { int score = CalcScoreForOverload(context, args, m_ExtOverloads[i], true); if (score > maxScore) { maxScore = score; bestOverload = m_ExtOverloads[i]; } } } if (bestOverload != null) { Cache(obj != null, args, bestOverload); return(bestOverload.Execute(script, obj, context, args)); } throw new ScriptRuntimeException("function call doesn't match any overload"); }
public static DynValue len(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue vs = args.AsType(0, "len", DataType.String, false); return(DynValue.NewNumber(vs.String.Length)); }
public static DynValue min(ScriptExecutionContext executionContext, CallbackArguments args) { return(exec2(args, "min", (x, y) => x < y ? x : y)); }
/// <summary> /// Builds the argument list. /// </summary> /// <param name="script">The script.</param> /// <param name="obj">The object.</param> /// <param name="context">The context.</param> /// <param name="args">The arguments.</param> /// <param name="outParams">Output: A list containing the indices of all "out" parameters, or null if no out parameters are specified.</param> /// <returns>The arguments, appropriately converted.</returns> protected virtual object[] BuildArgumentList(Script script, object obj, ScriptExecutionContext context, CallbackArguments args, out List <int> outParams) { var parameters = this.Parameters; var pars = new object[parameters.Length]; int j = args.IsMethodCall ? 1 : 0; outParams = null; for (int i = 0; i < pars.Length; i++) { // keep track of out and ref params if (parameters[i].Type.IsByRef) { if (outParams == null) { outParams = new List <int>(); } outParams.Add(i); } // if an ext method, we have an obj -> fill the first param if (this.ExtensionMethodType != null && obj != null && i == 0) { pars[i] = obj; } // else, fill types with a supported type else if (parameters[i].Type == typeof(Script)) { pars[i] = script; } else if (parameters[i].Type == typeof(ScriptExecutionContext)) { pars[i] = context; } else if (parameters[i].Type == typeof(CallbackArguments)) { pars[i] = args.SkipMethodCall(); } // else, ignore out params else if (parameters[i].IsOut) { pars[i] = null; } else if (i == parameters.Length - 1 && this.VarArgsArrayType != null) { var extraArgs = new List <DynValue>(); while (true) { var arg = args.RawGet(j, false); j += 1; if (arg != null) { extraArgs.Add(arg); } else { break; } } // here we have to worry we already have an array.. damn. We only support this for userdata. // remains to be analyzed what's the correct behavior here. For example, let's take a params object[].. // given a single table parameter, should it use it as an array or as an object itself ? if (extraArgs.Count == 1) { var arg = extraArgs[0]; if (arg.Type == DataType.UserData && arg.UserData.Object != null) { if (Framework.Do.IsAssignableFrom(this.VarArgsArrayType, arg.UserData.Object.GetType())) { pars[i] = arg.UserData.Object; continue; } } } // ok let's create an array, and loop var vararg = Array.CreateInstance(this.VarArgsElementType, extraArgs.Count); for (int ii = 0; ii < extraArgs.Count; ii++) { vararg.SetValue(ScriptToClrConversions.DynValueToObjectOfType(extraArgs[ii], this.VarArgsElementType, null, false), ii); } pars[i] = vararg; } // else, convert it else { var arg = args.RawGet(j, false) ?? DynValue.Void; pars[i] = ScriptToClrConversions.DynValueToObjectOfType(arg, parameters[i].Type, parameters[i].DefaultValue, parameters[i].HasDefaultValue); j += 1; } } return(pars); }
private static DynValue gmatch_aux_2(ScriptExecutionContext executionContext, CallbackArguments args) { return(executionContext.EmulateClassicCall(args, "gmatch", L => gmatch_aux(L, (GMatchAuxData)executionContext.AdditionalData))); }
public static DynValue sin(ScriptExecutionContext executionContext, CallbackArguments args) { return(exec1(args, "sin", (x) => - FixMath.Sin(x * 360))); }
public static DynValue __wrap_wrapper(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue handle = (DynValue)executionContext.AdditionalData; return(handle.Coroutine.Resume(args.GetArray())); }
public static DynValue pack(ScriptExecutionContext executionContext, CallbackArguments args) { return(TableModule.pack(executionContext, args)); }
private DynValue LuaIteratorCallback(ScriptExecutionContext executionContext, CallbackArguments args) { m_Prev = this.GetNext(m_Prev); return(m_Prev); }
private static object ArrayIndexerSet(object arrayObj, ScriptExecutionContext ctx, CallbackArguments args) { Array array = (Array)arrayObj; int[] indices = BuildArrayIndices(args, args.Count - 1); DynValue value = args[args.Count - 1]; Type elemType = array.GetType().GetElementType(); object objValue = ScriptToClrConversions.DynValueToObjectOfType(value, elemType, null, false); array.SetValue(objValue, indices); return(DynValue.Void); }
public static DynValue running(ScriptExecutionContext executionContext, CallbackArguments args) { Coroutine C = executionContext.GetCallingCoroutine(); return(DynValue.NewTuple(DynValue.NewCoroutine(C), DynValue.NewBoolean(C.State == CoroutineState.Main))); }
private static object ArrayIndexerGet(object arrayObj, ScriptExecutionContext ctx, CallbackArguments args) { Array array = (Array)arrayObj; int[] indices = BuildArrayIndices(args, args.Count); return(array.GetValue(indices)); }
public static DynValue flush(ScriptExecutionContext executionContext, CallbackArguments args) { FileUserDataBase outp = args.AsUserData<FileUserDataBase>(0, "close", true) ?? GetDefaultFile(executionContext, StandardFileType.StdOut); outp.flush(); return DynValue.True; }
/// <summary> /// The internal callback which actually executes the method /// </summary> /// <param name="script">The script.</param> /// <param name="obj">The object.</param> /// <param name="context">The context.</param> /// <param name="args">The arguments.</param> public abstract DynValue Execute(Script script, object obj, ScriptExecutionContext context, CallbackArguments args);
public static DynValue output(ScriptExecutionContext executionContext, CallbackArguments args) { return HandleDefaultStreamSetter(executionContext, args, StandardFileType.StdOut); }
/// <summary> /// Calculates the score for the overload. /// </summary> /// <param name="context">The context.</param> /// <param name="args">The arguments.</param> /// <param name="method">The method.</param> /// <param name="isExtMethod">if set to <c>true</c>, is an extension method.</param> /// <returns></returns> private int CalcScoreForOverload(ScriptExecutionContext context, CallbackArguments args, IOverloadableMemberDescriptor method, bool isExtMethod) { int totalScore = ScriptToClrConversions.WEIGHT_EXACT_MATCH; int argsBase = args.IsMethodCall ? 1 : 0; int argsCnt = argsBase; bool varArgsUsed = false; for (int i = 0; i < method.Parameters.Length; i++) { if (isExtMethod && i == 0) { continue; } if (method.Parameters[i].IsOut) { continue; } Type parameterType = method.Parameters[i].Type; if ((parameterType == typeof(Script)) || (parameterType == typeof(ScriptExecutionContext)) || (parameterType == typeof(CallbackArguments))) { continue; } if (i == method.Parameters.Length - 1 && method.VarArgsArrayType != null) { int varargCnt = 0; DynValue firstArg = DynValue.Nil; int scoreBeforeVargars = totalScore; // update score for varargs while (true) { var arg = args.RawGet(argsCnt, false); if (arg.IsNil()) { break; } if (firstArg.IsNil()) { firstArg = arg; } argsCnt += 1; varargCnt += 1; int score = CalcScoreForSingleArgument(method.Parameters[i], method.VarArgsElementType, arg, isOptional: false); totalScore = Math.Min(totalScore, score); } // check if exact-match if (varargCnt == 1) { if (firstArg.Type == DataType.UserData && firstArg.UserData.Object != null) { if (method.VarArgsArrayType.IsAssignableFrom(firstArg.UserData.Object.GetType())) { totalScore = scoreBeforeVargars; continue; } } } // apply varargs penalty to score if (varargCnt == 0) { totalScore = Math.Min(totalScore, ScriptToClrConversions.WEIGHT_VARARGS_EMPTY); } varArgsUsed = true; } else { var arg = args.RawGet(argsCnt, false); int score = CalcScoreForSingleArgument(method.Parameters[i], parameterType, arg, method.Parameters[i].HasDefaultValue); totalScore = Math.Min(totalScore, score); argsCnt += 1; } } if (totalScore > 0) { if ((args.Count - argsBase) <= method.Parameters.Length) { totalScore += ScriptToClrConversions.WEIGHT_NO_EXTRA_PARAMS_BONUS; totalScore *= 1000; } else if (varArgsUsed) { totalScore -= ScriptToClrConversions.WEIGHT_VARARGS_MALUS; totalScore *= 1000; } else { totalScore *= 1000; totalScore -= ScriptToClrConversions.WEIGHT_EXTRA_PARAMS_MALUS * ((args.Count - argsBase) - method.Parameters.Length); totalScore = Math.Max(1, totalScore); } } #if DEBUG_OVERLOAD_RESOLVER System.Diagnostics.Debug.WriteLine(string.Format("[OVERLOAD] : Score {0} for method {1}", totalScore, method.SortDiscriminant)); #endif return(totalScore); }
private static DynValue __tostring_continuation(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue b = args[0].ToScalar(); if (b.IsNil()) { return(b); } if (b.Type != DataType.String) { throw new ScriptRuntimeException("'tostring' must return a string"); } return(b); }
public static DynValue gmatch(ScriptExecutionContext executionContext, CallbackArguments args) { return(executionContext.EmulateClassicCall(args, "gmatch", KopiLua_StringLib.str_gmatch)); }
public static DynValue error(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue message = args.AsType(0, "error", DataType.String, false); throw new ScriptRuntimeException(message.String); // { DoNotDecorateMessage = true }; }
public static DynValue flr(ScriptExecutionContext executionContext, CallbackArguments args) { return(exec1(args, "flr", (x) => FixMath.Floor(x))); }
public static DynValue collectgarbage(ScriptExecutionContext executionContext, CallbackArguments args) { DynValue opt = args[0]; string mode = opt.CastToString(); if (mode == null || mode == "collect" || mode == "restart") { #if PCL || ENABLE_DOTNET GC.Collect(); #else GC.Collect(2, GCCollectionMode.Forced); #endif } return(DynValue.Nil); }
private static DynValue HandleDefaultStreamSetter(ScriptExecutionContext executionContext, CallbackArguments args, StandardFileType defaultFiles) { if (args.Count == 0 || args[0].IsNil()) { var file = GetDefaultFile(executionContext, defaultFiles); return UserData.Create(file); } FileUserDataBase inp = null; if (args[0].Type == DataType.String || args[0].Type == DataType.Number) { string fileName = args[0].CastToString(); inp = Open(executionContext, fileName, GetUTF8Encoding(), defaultFiles == StandardFileType.StdIn ? "r" : "w"); } else { inp = args.AsUserData<FileUserDataBase>(0, defaultFiles == StandardFileType.StdIn ? "input" : "output", false); } SetDefaultFile(executionContext, defaultFiles, inp); return UserData.Create(inp); }
public static DynValue btest(ScriptExecutionContext executionContext, CallbackArguments args) { return(DynValue.NewBoolean(0 != Bitwise("btest", args, (x, y) => x & y))); }
public static DynValue write(ScriptExecutionContext executionContext, CallbackArguments args) { FileUserDataBase file = GetDefaultFile(executionContext, StandardFileType.StdOut); return file.write(executionContext, args); }
public static DynValue tmpfile(ScriptExecutionContext executionContext, CallbackArguments args) { string tmpfilename = Script.GlobalOptions.Platform.IO_OS_GetTempFilename(); FileUserDataBase file = Open(executionContext, tmpfilename, GetUTF8Encoding(), "w"); return UserData.Create(file); }
public static DynValue bxor(ScriptExecutionContext executionContext, CallbackArguments args) { return(DynValue.NewNumber(Bitwise("bxor", args, (x, y) => x ^ y))); }
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 d; if (double.TryParse(e.String, NumberStyles.Any, CultureInfo.InvariantCulture, out d)) { return(DynValue.NewNumber(d)); } return(DynValue.Nil); } else { //!COMPAT: tonumber supports only 2,8,10 or 16 as base //UPDATE: added support for 3-9 base numbers 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)); }; int bb = (int)b.Number; uint uiv = 0; if (bb == 2 || bb == 8 || bb == 10 || bb == 16) { uiv = Convert.ToUInt32(ee.String.Trim(), bb); } else if (bb < 10 && bb > 2) // Support for 3, 4, 5, 6, 7 and 9 based numbers { foreach (char digit in ee.String.Trim()) { int value = digit - 48; if (value < 0 || value >= bb) { throw new ScriptRuntimeException("bad argument #1 to 'tonumber' (invalid character)"); } uiv = (uint)(uiv * bb) + (uint)value; } } else { throw new ScriptRuntimeException("bad argument #2 to 'tonumber' (base out of range)"); } return(DynValue.NewNumber(uiv)); } }