public DynValue Index(ExecutionControlToken ecToken, Script script, DynValue index, bool isDirectIndexing)
        {
            if (index.Type == DataType.String)
            {
                string idx = index.String;

                if (idx == "Current" || idx == "current")
                {
                    return(DynValue.FromObject(script, m_Enumerator.Current));
                }

                if (idx == "MoveNext" || idx == "moveNext" || idx == "move_next")
                {
                    return(DynValue.NewCallback((ctx, args) => DynValue.NewBoolean(m_Enumerator.MoveNext())));
                }

                if (idx == "Reset" || idx == "reset")
                {
                    return(DynValue.NewCallback((ctx, args) =>
                    {
                        this.Reset();
                        return DynValue.Nil;
                    }));
                }
            }

            return(null);
        }
示例#2
0
        private int Internal_InvokeUnaryMetaMethod(ExecutionControlToken ecToken, DynValue op1, string eventName, int instructionPtr)
        {
            DynValue m = null;

            if (op1.Type == DataType.UserData)
            {
                m = op1.UserData.Descriptor.MetaIndex(ecToken, m_Script, op1.UserData.Object, eventName);
            }

            if (m == null)
            {
                var op1_MetaTable = GetMetatable(op1);

                if (op1_MetaTable != null)
                {
                    DynValue meta1 = op1_MetaTable.RawGet(eventName);
                    if (meta1 != null && meta1.IsNotNil())
                    {
                        m = meta1;
                    }
                }
            }

            if (m != null)
            {
                m_ValueStack.Push(m);
                m_ValueStack.Push(op1);
                return(Internal_ExecCall(ecToken, 1, instructionPtr));
            }
            else
            {
                return(-1);
            }
        }
        /// <summary>
        /// Gets a "meta" operation on this userdata.
        /// In this specific case, only the concat operator is supported, only on flags enums and it implements the
        /// 'or' operator.
        /// </summary>
        /// <param name="ecToken">The execution control token of the script processing thread</param>
        /// <param name="script"></param>
        /// <param name="obj"></param>
        /// <param name="metaname"></param>
        /// <returns></returns>
        public override DynValue MetaIndex(ExecutionControlToken ecToken, Script script, object obj, string metaname)
        {
            if (metaname == "__concat" && IsFlags)
            {
                return(DynValue.NewCallback(Callback_Or));
            }

            return(null);
        }
        public DynValue MetaIndex(ExecutionControlToken ecToken, Script script, string metaname)
        {
            if (metaname == "__call")
            {
                return(DynValue.NewCallback(this.LuaIteratorCallback));
            }

            return(null);
        }
示例#5
0
        /// <summary>
        /// Performs an "index" "get" operation. This tries to resolve minor variations of member names.
        /// </summary>
        /// <param name="ecToken">The execution control token of the script processing thread</param>
        /// <param name="script">The script originating the request</param>
        /// <param name="obj">The object (null if a static request is done)</param>
        /// <param name="index">The index.</param>
        /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param>
        /// <returns></returns>
        public virtual DynValue Index(ExecutionControlToken ecToken, Script script, object obj, DynValue index, bool isDirectIndexing)
        {
            if (!isDirectIndexing)
            {
                IMemberDescriptor mdesc = m_Members
                                          .GetOrDefault(SPECIALNAME_INDEXER_GET)
                                          .WithAccessOrNull(MemberDescriptorAccess.CanExecute);

                if (mdesc != null)
                {
                    return(ExecuteIndexer(ecToken, mdesc, script, obj, index, null));
                }
            }

            index = index.ToScalar();

            if (index.Type != DataType.String)
            {
                return(null);
            }

            DynValue v = TryIndex(script, obj, index.String);

            if (v == null)
            {
                v = TryIndex(script, obj, UpperFirstLetter(index.String));
            }
            if (v == null)
            {
                v = TryIndex(script, obj, Camelify(index.String));
            }
            if (v == null)
            {
                v = TryIndex(script, obj, UpperFirstLetter(Camelify(index.String)));
            }

            if (v == null && m_ExtMethodsVersion < UserData.GetExtensionMethodsChangeVersion())
            {
                m_ExtMethodsVersion = UserData.GetExtensionMethodsChangeVersion();

                v = TryIndexOnExtMethod(script, obj, index.String);
                if (v == null)
                {
                    v = TryIndexOnExtMethod(script, obj, UpperFirstLetter(index.String));
                }
                if (v == null)
                {
                    v = TryIndexOnExtMethod(script, obj, Camelify(index.String));
                }
                if (v == null)
                {
                    v = TryIndexOnExtMethod(script, obj, UpperFirstLetter(Camelify(index.String)));
                }
            }

            return(v);
        }
示例#6
0
 /// <summary>
 /// Performs an "index" "set" operation.
 /// </summary>
 /// <param name="ecToken">The execution control token of the script processing thread</param>
 /// <param name="script">The script originating the request</param>
 /// <param name="obj">The object (null if a static request is done)</param>
 /// <param name="index">The index.</param>
 /// <param name="value">The value to be set</param>
 /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param>
 /// <returns></returns>
 public bool SetIndex(ExecutionControlToken ecToken, Script script, object obj, DynValue index, DynValue value, bool isNameIndex)
 {
     foreach (IUserDataDescriptor dd in m_Descriptors)
     {
         if (dd.SetIndex(ecToken, script, obj, index, value, isNameIndex))
         {
             return(true);
         }
     }
     return(false);
 }
示例#7
0
        /// <summary>
        /// Gets a "meta" operation on this userdata. If a descriptor does not support this functionality,
        /// it should return "null" (not a nil).
        /// See <see cref="IUserDataDescriptor.MetaIndex" /> for further details.
        ///
        /// If a method exists marked with <see cref="MoonSharpUserDataMetamethodAttribute" /> for the specific
        /// metamethod requested, that method is returned.
        ///
        /// If the above fails, the following dispatching occur:
        ///
        /// __add, __sub, __mul, __div, __mod and __unm are dispatched to C# operator overloads (if they exist)
        /// __eq is dispatched to System.Object.Equals.
        /// __lt and __le are dispatched IComparable.Compare, if the type implements IComparable or IComparable{object}
        /// __len is dispatched to Length and Count properties, if those exist.
        /// __iterator is handled if the object implements IEnumerable or IEnumerator.
        /// __tonumber is dispatched to implicit or explicit conversion operators to standard numeric types.
        /// __tobool is dispatched to an implicit or explicit conversion operator to bool. If that fails, operator true is used.
        ///
        /// <param name="ecToken">The execution control token of the script processing thread</param>
        /// <param name="script">The script originating the request</param>
        /// <param name="obj">The object (null if a static request is done)</param>
        /// <param name="metaname">The name of the metamember.</param>
        /// </summary>
        public virtual DynValue MetaIndex(ExecutionControlToken ecToken, Script script, object obj, string metaname)
        {
            var desc = m_MetaMembers.GetOrDefault(metaname);

            if (desc != null)
            {
                return(desc.GetValue(script, obj));
            }

            switch (metaname)
            {
            case "__add":
                return(this.DispatchMetaOnMethod(script, obj, "op_Addition"));

            case "__sub":
                return(this.DispatchMetaOnMethod(script, obj, "op_Subtraction"));

            case "__mul":
                return(this.DispatchMetaOnMethod(script, obj, "op_Multiply"));

            case "__div":
                return(this.DispatchMetaOnMethod(script, obj, "op_Division"));

            case "__mod":
                return(this.DispatchMetaOnMethod(script, obj, "op_Modulus"));

            case "__unm":
                return(this.DispatchMetaOnMethod(script, obj, "op_UnaryNegation"));

            case "__eq":
                return(this.MultiDispatchEqual(script, obj));

            case "__lt":
                return(this.MultiDispatchLessThan(script, obj));

            case "__le":
                return(this.MultiDispatchLessThanOrEqual(script, obj));

            case "__len":
                return(this.TryDispatchLength(script, obj));

            case "__tonumber":
                return(this.TryDispatchToNumber(script, obj));

            case "__tobool":
                return(this.TryDispatchToBool(script, obj));

            case "__iterator":
                return(ClrToScriptConversions.EnumerationToDynValue(script, obj));

            default:
                return(null);
            }
        }
示例#8
0
        /// <summary>
        /// Gets a "meta" operation on this userdata. If a descriptor does not support this functionality,
        /// it should return "null" (not a nil).
        /// These standard metamethods can be supported (the return value should be a function accepting the
        /// classic parameters of the corresponding metamethod):
        /// __add, __sub, __mul, __div, __div, __pow, __unm, __eq, __lt, __le, __lt, __len, __concat,
        /// __pairs, __ipairs, __iterator, __call
        /// These standard metamethods are supported through other calls for efficiency:
        /// __index, __newindex, __tostring
        /// </summary>
        /// <param name="ecToken">The execution control token of the script processing thread</param>
        /// <param name="script">The script originating the request</param>
        /// <param name="obj">The object (null if a static request is done)</param>
        /// <param name="metaname">The name of the metamember.</param>
        /// <returns></returns>
        public DynValue MetaIndex(ExecutionControlToken ecToken, Script script, object obj, string metaname)
        {
            foreach (IUserDataDescriptor dd in m_Descriptors)
            {
                DynValue v = dd.MetaIndex(ecToken, script, obj, metaname);

                if (v != null)
                {
                    return(v);
                }
            }
            return(null);
        }
示例#9
0
        /// <summary>
        /// Performs an "index" "get" operation.
        /// </summary>
        /// <param name="ecToken">The execution control token of the script processing thread</param>
        /// <param name="script">The script originating the request</param>
        /// <param name="obj">The object (null if a static request is done)</param>
        /// <param name="index">The index.</param>
        /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param>
        /// <returns></returns>
        public DynValue Index(ExecutionControlToken ecToken, Script script, object obj, DynValue index, bool isNameIndex)
        {
            foreach (IUserDataDescriptor dd in m_Descriptors)
            {
                DynValue v = dd.Index(ecToken, script, obj, index, isNameIndex);

                if (v != null)
                {
                    return(v);
                }
            }
            return(null);
        }
        internal DynValue GetMetamethod(ExecutionControlToken ecToken, DynValue value, string metamethod)
        {
            if (value.Type == DataType.UserData)
            {
                DynValue v = value.UserData.Descriptor.MetaIndex(ecToken, m_Script, value.UserData.Object, metamethod);
                if (v != null)
                {
                    return(v);
                }
            }

            return(GetMetamethodRaw(value, metamethod));
        }
示例#11
0
        internal DynValue GetBinaryMetamethod(ExecutionControlToken ecToken, DynValue op1, DynValue op2,
                                              string eventName)
        {
            var op1_MetaTable = this.GetMetatable(op1);

            if (op1_MetaTable != null)
            {
                var meta1 = op1_MetaTable.RawGet(eventName);
                if (meta1 != null && meta1.IsNotNil())
                {
                    return(meta1);
                }
            }

            var op2_MetaTable = this.GetMetatable(op2);

            if (op2_MetaTable != null)
            {
                var meta2 = op2_MetaTable.RawGet(eventName);
                if (meta2 != null && meta2.IsNotNil())
                {
                    return(meta2);
                }
            }

            if (op1.Type == DataType.UserData)
            {
                var meta = op1.UserData.Descriptor.MetaIndex(ecToken, _script,
                                                             op1.UserData.Object, eventName);

                if (meta != null)
                {
                    return(meta);
                }
            }

            if (op2.Type == DataType.UserData)
            {
                var meta = op2.UserData.Descriptor.MetaIndex(ecToken, _script,
                                                             op2.UserData.Object, eventName);

                if (meta != null)
                {
                    return(meta);
                }
            }

            return(null);
        }
示例#12
0
        public DynValue Index(ExecutionControlToken ecToken, Script script, DynValue index, bool isDirectIndexing)
        {
            if (index.Type == DataType.String)
            {
                if (index.String == "add")
                {
                    return(DynValue.NewCallback((c, a) => m_AddCallback(m_Object, c, a)));
                }
                else if (index.String == "remove")
                {
                    return(DynValue.NewCallback((c, a) => m_RemoveCallback(m_Object, c, a)));
                }
            }

            throw new ScriptRuntimeException("Events only support add and remove methods");
        }
示例#13
0
        public DynValue Index(ExecutionControlToken ecToken, Script script, DynValue index, bool isDirectIndexing)
        {
            if (index.Type != DataType.String)
            {
                throw new ScriptRuntimeException("string property was expected");
            }

            lock (_lock)
            {
                if (_values.ContainsKey(index.String))
                {
                    return(_values[index.String].Clone());
                }

                return(DynValue.Nil);
            }
        }
示例#14
0
        /// <summary>
        /// Executes the specified indexer method.
        /// </summary>
        /// <param name="ecToken">The execution control token used to cancel scripts if needed.</param>
        /// <param name="mdesc">The method descriptor</param>
        /// <param name="script">The script.</param>
        /// <param name="obj">The object.</param>
        /// <param name="index">The indexer parameter</param>
        /// <param name="value">The dynvalue to set on a setter, or null.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        protected virtual DynValue ExecuteIndexer(ExecutionControlToken ecToken, IMemberDescriptor mdesc, Script script,
                                                  object obj, DynValue index, DynValue value)
        {
            IList <DynValue> values;

            if (index.Type == DataType.Tuple)
            {
                if (value == null)
                {
                    values = index.Tuple;
                }
                else
                {
                    values = new List <DynValue>(index.Tuple);
                    values.Add(value);
                }
            }
            else
            {
                if (value == null)
                {
                    values = new[] { index };
                }
                else
                {
                    values = new[] { index, value };
                }
            }

            var args    = new CallbackArguments(values, false);
            var execCtx = script.CreateDynamicExecutionContext(ecToken);

            var v = mdesc.GetValue(script, obj);

            if (v.Type != DataType.ClrFunction)
            {
                throw new ScriptRuntimeException("a clr callback was expected in member {0}, while a {1} was found",
                                                 mdesc.Name, v.Type);
            }

            return(v.Callback.ClrCallback(execCtx, args));
        }
示例#15
0
        /// <summary>
        /// Performs an "index" "set" operation. This tries to resolve minor variations of member names.
        /// </summary>
        /// <param name="ecToken">The execution control token used to cancel scripts if needed.</param>
        /// <param name="script">The script originating the request</param>
        /// <param name="obj">The object (null if a static request is done)</param>
        /// <param name="index">The index.</param>
        /// <param name="value">The value to be set</param>
        /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param>
        public virtual bool SetIndex(ExecutionControlToken ecToken, Script script, object obj, DynValue index,
                                     DynValue value, bool isDirectIndexing)
        {
            if (!isDirectIndexing)
            {
                var mdesc = m_Members
                            .GetOrDefault(SPECIALNAME_INDEXER_SET)
                            .WithAccessOrNull(MemberDescriptorAccess.CanExecute);

                if (mdesc != null)
                {
                    this.ExecuteIndexer(ecToken, mdesc, script, obj, index, value);
                    return(true);
                }
            }

            index = index.ToScalar();

            if (index.Type != DataType.String)
            {
                return(false);
            }

            bool v = this.TrySetIndex(script, obj, index.String, value);

            if (!v)
            {
                v = this.TrySetIndex(script, obj, UpperFirstLetter(index.String), value);
            }

            if (!v)
            {
                v = this.TrySetIndex(script, obj, Camelify(index.String), value);
            }

            if (!v)
            {
                v = this.TrySetIndex(script, obj, UpperFirstLetter(Camelify(index.String)), value);
            }

            return(v);
        }
示例#16
0
        private int Internal_InvokeBinaryMetaMethod(ExecutionControlToken ecToken, DynValue l, DynValue r, string eventName, int instructionPtr, DynValue extraPush = null)
        {
            var m = GetBinaryMetamethod(ecToken, l, r, eventName);

            if (m != null)
            {
                if (extraPush != null)
                {
                    m_ValueStack.Push(extraPush);
                }

                m_ValueStack.Push(m);
                m_ValueStack.Push(l);
                m_ValueStack.Push(r);
                return(Internal_ExecCall(ecToken, 2, instructionPtr));
            }
            else
            {
                return(-1);
            }
        }
示例#17
0
        public bool SetIndex(ExecutionControlToken ecToken, Script script, DynValue index, DynValue value, bool isDirectIndexing)
        {
            if (index.Type != DataType.String)
            {
                throw new ScriptRuntimeException("string property was expected");
            }

            lock (_lock)
            {
                switch (value.Type)
                {
                case DataType.Void:
                case DataType.Nil:
                    _values.Remove(index.String);
                    return(true);

                case DataType.UserData:
                    // HERE YOU CAN CHOOSE A DIFFERENT POLICY.. AND TRY TO SHARE IF NEEDED. DANGEROUS, THOUGH.
                    throw new ScriptRuntimeException("Cannot share a value of type {0}", value.Type.ToErrorTypeString());

                case DataType.ClrFunction:
                    // HERE YOU CAN CHOOSE A DIFFERENT POLICY.. AND TRY TO SHARE IF NEEDED. DANGEROUS, THOUGH.
                    throw new ScriptRuntimeException("Cannot share a value of type {0}", value.Type.ToErrorTypeString());

                case DataType.Boolean:
                case DataType.Number:
                case DataType.String:
                    _values[index.String] = value.Clone();
                    return(true);

                case DataType.Table:
                    _values[index.String] = value.Clone();
                    return(true);

                default:
                    throw new ScriptRuntimeException("Cannot share a value of type {0}", value.Type.ToErrorTypeString());
                }
            }
        }
示例#18
0
        public DynValue Call(ExecutionControlToken ecToken, DynValue function, DynValue[] args)
        {
            List <Processor> coroutinesStack = m_Parent != null ? m_Parent.m_CoroutinesStack : this.m_CoroutinesStack;

            if (coroutinesStack.Count > 0 && coroutinesStack[coroutinesStack.Count - 1] != this)
            {
                return(coroutinesStack[coroutinesStack.Count - 1].Call(ecToken, function, args));
            }

            EnterProcessor();

            try
            {
                var stopwatch = this.m_Script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Execution);

                m_CanYield = false;

                try
                {
                    int entrypoint = PushClrToScriptStackFrame(CallStackItemFlags.CallEntryPoint, function, args);
                    return(Processing_Loop(ecToken, entrypoint));
                }
                finally
                {
                    m_CanYield = true;

                    if (stopwatch != null)
                    {
                        stopwatch.Dispose();
                    }
                }
            }
            finally
            {
                LeaveProcessor();
            }
        }
 public bool SetIndex(ExecutionControlToken ecToken, Script script, DynValue index, DynValue value,
                      bool isDirectIndexing)
 {
     return(false);
 }
示例#20
0
 public DynValue MetaIndex(ExecutionControlToken ecToken, Script script, string metaname)
 {
     return(null);
 }
示例#21
0
 public bool SetIndex(ExecutionControlToken ecToken, Script script, DynValue index, DynValue value, bool isDirectIndexing)
 {
     throw new ScriptRuntimeException("Events do not have settable fields");
 }
 /// <summary>
 /// Performs an "index" "get" operation.
 /// </summary>
 /// <param name="ecToken">The execution control token of the script processing thread</param>
 /// <param name="script">The script originating the request</param>
 /// <param name="obj">The object (null if a static request is done)</param>
 /// <param name="index">The index.</param>
 /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param>
 public DynValue Index(ExecutionControlToken ecToken, Script script, object obj, DynValue index,
                       bool isDirectIndexing)
 {
     return(this.InnerDescriptor.Index(ecToken, script, this.Proxy(obj), index, isDirectIndexing));
 }
示例#23
0
        /// <summary>
        /// Executes a Lua script asynchronously.
        /// </summary>
        /// <param name="luaCode"></param>
        public async Task ExecuteAsync(string luaCode)
        {
            if (string.IsNullOrWhiteSpace(luaCode))
            {
                return;
            }

            await Application.Current.Dispatcher.InvokeAsync(new Action(async() =>
            {
                try
                {
                    // Setup Lua
                    var lua = new Script();
                    lua.Options.CheckThreadAccess = false;
                    UserData.RegisterType <LuaCommands>();
                    UserData.RegisterType <LuaGlobalVariables>();

                    // Custom Lua Commands
                    var luaCmd = UserData.Create(new LuaCommands(_interpreter, _random));
                    lua.Globals.Set("lua", luaCmd);

                    // Set the global variables that are specifically only available in Lua.
                    lua.Globals["global"] = _luaGlobalVariables;

                    // If there is a Lua global shared set of code run it, try catch it in case there
                    // is a problem with it, we don't want it to interfere with everything if there is
                    // an issue with it, we DO want to show the user that though.
                    var executionControlToken = new ExecutionControlToken();

                    try
                    {
                        if (!string.IsNullOrWhiteSpace(App.Settings?.ProfileSettings?.LuaGlobalScript))
                        {
                            await lua.DoStringAsync(executionControlToken, App.Settings.ProfileSettings.LuaGlobalScript);
                        }
                    }
                    catch (Exception ex)
                    {
                        _interpreter.Conveyor.EchoLog("There was an error in the global Lua file.", LogType.Error);
                        _interpreter.Conveyor.EchoLog($"Lua: {ex.Message}", LogType.Error);
                    }

                    await lua.DoStringAsync(executionControlToken, luaCode);
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        if (ex.InnerException.Message.Contains("abort"))
                        {
                            // TODO - Make this a setting so that it can be tailored (the command that is sent, e.g. the ~).
                            // Cancel pending sends with the mud in case something went haywire
                            _interpreter.Send("~", true, false);
                            _interpreter.Conveyor.EchoLog("All active Lua scripts have been terminated.", LogType.Error);
                        }
                        else
                        {
                            var exInner = ((InterpreterException)ex.InnerException);
                            _interpreter.Send("~", true, false);
                            _interpreter.Conveyor.EchoLog($"--> {exInner.DecoratedMessage}", LogType.Error);
                        }
                    }
                    else
                    {
                        _interpreter.Send("~", true, false);
                        _interpreter.Conveyor.EchoLog(ex.Message, LogType.Error);
                    }
                }
            }), DispatcherPriority.Normal);
        }
        private static DynValue SetErrorHandlerStrategy(ExecutionControlToken ecToken,
                                                        string funcName,
                                                        ScriptExecutionContext executionContext,
                                                        CallbackArguments args,
                                                        DynValue handlerBeforeUnwind)
        {
            DynValue v = args[0];

            DynValue[] a = new DynValue[args.Count - 1];

            for (int i = 1; i < args.Count; i++)
            {
                a[i - 1] = args[i];
            }

            if (args[0].Type == DataType.ClrFunction)
            {
                try
                {
                    DynValue 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
                        }));
                    }
                    else 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);
                    }
                    else
                    {
                        return(DynValue.NewTupleNested(DynValue.True, ret));
                    }
                }
                catch (ScriptRuntimeException ex)
                {
                    executionContext.PerformMessageDecorationBeforeUnwind(handlerBeforeUnwind, ex);
                    return(DynValue.NewTupleNested(DynValue.False, DynValue.NewString(ex.DecoratedMessage)));
                }
            }
            else if (args[0].Type != DataType.Function)
            {
                return(DynValue.NewTupleNested(DynValue.False, DynValue.NewString("attempt to " + funcName + " a non-function")));
            }
            else
            {
                return(DynValue.NewTailCallReq(new TailCallData()
                {
                    Args = a,
                    Function = v,
                    Continuation = new CallbackFunction(pcall_continuation, funcName),
                    ErrorHandler = new CallbackFunction(pcall_onerror, funcName),
                    ErrorHandlerBeforeUnwind = handlerBeforeUnwind
                }));
            }
        }
 /// <inheritdoc/>
 public DynValue Index(ExecutionControlToken ecToken, Script script, object obj, DynValue index,
                       bool isDirectIndexing)
 {
     return(null);
 }
示例#26
0
        /// <summary>
        /// The Loaded event for the Window where we will execute code that should run when the Window
        /// is first put into place.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // The Conveyor will be passed around to other objects so that they can interact with the UI.  This Conveyor may have
            // state so it's important to re-use this object unless sandboxing is needed.
            Conveyor = new Conveyor();

            // The settings for the app load in the app startup, they will then try to load the last profile
            // that was used.
            Conveyor.EchoLog($"Settings Folder: {App.Settings.AppDataDirectory}", LogType.Information);
            Conveyor.EchoLog($"Settings File:   {App.Settings.AvalonSettingsFile}", LogType.Information);
            Conveyor.EchoLog($"Profiles Folder: {App.Settings.AvalonSettings.SaveDirectory}", LogType.Information);

            // Parse the command line arguments to see if a profile was specified.
            var args = Environment.GetCommandLineArgs();


            // Try to load the last profile loaded, if not found create a new profile.
            if (File.Exists(App.Settings.AvalonSettings.LastLoadedProfilePath))
            {
                App.Settings.LoadSettings(App.Settings.AvalonSettings.LastLoadedProfilePath);
                Conveyor.EchoLog($"Settings Loaded: {App.Settings.AvalonSettings.LastLoadedProfilePath}", LogType.Information);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(App.Settings.AvalonSettings.LastLoadedProfilePath))
                {
                    Conveyor.EchoLog($"New Profile being created.", LogType.Information);
                }
                else
                {
                    Conveyor.EchoLog($"Last Profile Loaded Not Found: {App.Settings.AvalonSettings.LastLoadedProfilePath}", LogType.Warning);
                }
            }


            // TODO - Figure out a better way to inject a single Conveyor, maybe static in App?
            // Inject the Conveyor into the Triggers.
            foreach (var trigger in App.Settings.ProfileSettings.TriggerList)
            {
                trigger.Conveyor = Conveyor;
            }

            // Wire up any events that have to be wired up through code.
            TextInput.Editor.PreviewKeyDown += this.Editor_PreviewKeyDown;
            AddHandler(TabControlEx.NetworkButtonClickEvent, new RoutedEventHandler(NetworkButton_Click));
            AddHandler(TabControlEx.SettingsButtonClickEvent, new RoutedEventHandler(SettingsButton_Click));

            // Pass the necessary reference from this page to the Interpreter.
            Interp = new Interpreter(this.Conveyor);

            // Setup the handler so when it wants to write to the main window it can by raising the echo event.
            Interp.Echo += this.InterpreterEcho;

            // Setup Lua
            Lua = new Script();
            Lua.Options.CheckThreadAccess = false;
            UserData.RegisterType <LuaCommands>();

            // create a userdata, again, explicitly.
            var luaCmd = UserData.Create(new LuaCommands(Interp));

            Lua.Globals.Set("Cmd", luaCmd);
            LuaControl = new ExecutionControlToken();

            // Setup the tick timer.
            TickTimer = new TickTimer(Conveyor);

            // Setup the auto complete commands.  If they're found refresh them, if they're not
            // report it to the terminal window.  It should -always be found-.
            RefreshAutoCompleteEntries();

            // Auto connect to the game if the setting is set.
            if (App.Settings.ProfileSettings.AutoConnect)
            {
                NetworkButton_Click(null, null);
            }

            // Is there an auto execute command or set of commands to run?
            if (!string.IsNullOrWhiteSpace(App.Settings.ProfileSettings.AutoExecuteCommand))
            {
                Interp.Send(App.Settings.ProfileSettings.AutoExecuteCommand, true, false);
            }

            // Finally, all is done, set the focus to the command box.
            TextInput.Focus();
        }
 /// <summary>
 /// Performs an "index" "set" operation.
 /// </summary>
 /// <param name="ecToken">The execution control token of the script processing thread</param>
 /// <param name="script">The script originating the request</param>
 /// <param name="obj">The object (null if a static request is done)</param>
 /// <param name="index">The index.</param>
 /// <param name="value">The value to be set</param>
 /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param>
 /// <returns></returns>
 public bool SetIndex(ExecutionControlToken ecToken, Script script, object obj, DynValue index, DynValue value, bool isDirectIndexing)
 {
     return(m_ProxyDescriptor.SetIndex(ecToken, script, Proxy(obj), index, value, isDirectIndexing));
 }
 /// <summary>
 /// Gets a "meta" operation on this userdata. If a descriptor does not support this functionality,
 /// it should return "null" (not a nil).
 /// These standard metamethods can be supported (the return value should be a function accepting the
 /// classic parameters of the corresponding metamethod):
 /// __add, __sub, __mul, __div, __div, __pow, __unm, __eq, __lt, __le, __lt, __len, __concat,
 /// __pairs, __ipairs, __iterator, __call
 /// These standard metamethods are supported through other calls for efficiency:
 /// __index, __newindex, __tostring
 /// </summary>
 /// <param name="ecToken">The execution control token of the script processing thread</param>
 /// <param name="script">The script originating the request</param>
 /// <param name="obj">The object (null if a static request is done)</param>
 /// <param name="metaname">The name of the metamember.</param>
 /// <returns></returns>
 public DynValue MetaIndex(ExecutionControlToken ecToken, Script script, object obj, string metaname)
 {
     return(m_ProxyDescriptor.MetaIndex(ecToken, script, Proxy(obj), metaname));
 }