Пример #1
0
 public void CodePlexExample4a()
 {
     using (Lua l = new Lua())
     {
         dynamic   dg = l.CreateEnvironment();
         LuaResult r  = dg.dochunk("t = { a = 2, b = 4 };" +
                                   "t.add = function(self)" +
                                   "  return self.a + self.b;" +
                                   "end;" +
                                   "function t.add1(self)" +
                                   "  return self.a + self.b;" +
                                   "end;" +
                                   "t:add2 = function (self)" +
                                   "  return self.a + self.b;" +
                                   "end;" +
                                   "function t:add3()" +
                                   "  return self.a + self.b;" +
                                   "end;" +
                                   "return t:add(), t:add2(), t:add3(), t.add(t), t.add2(t), t.add3(t);",
                                   "test.lua");
         Console.WriteLine(r[0]);
         Console.WriteLine(r[1]);
         Console.WriteLine(r[2]);
         Console.WriteLine(r[3]);
         Console.WriteLine(r[4]);
         Console.WriteLine(r[5]);
         Console.WriteLine(dg.t.add(dg.t)[0]);
         Console.WriteLine(dg.t.add2()[0]);
         Console.WriteLine(dg.t.add3()[0]);
     }
 }
Пример #2
0
        }         // CompareStringKey

        public static T ReturnOptionalValue <T>(this LuaTable table, string name, T @default, bool ignoreCase = false, bool rawGet = false)
        {
            var value = table.GetMemberValue(name, ignoreCase, rawGet);

            if (value == null)
            {
                return(@default);
            }
            else
            {
                if (Lua.RtInvokeable(value))
                {
                    value = new LuaResult(Lua.RtInvoke(value))[0];
                }

                if (value == null)
                {
                    return(@default);
                }
                try
                {
                    return(value.ChangeType <T>());
                }
                catch
                {
                    return(@default);
                }
            }
        } // func ReturnOptionalValue
Пример #3
0
        } // proc TokenTest

        #endregion

        #region -- TestConstants ----------------------------------------------------------

        private bool TestConstant(Lua l, string sVarValue, object result)
        {
            Debug.Print("Test: " + sVarValue);
            LuaResult r = l.CreateEnvironment().DoChunk("return " + sVarValue + ";", "test.lua");

            return(Object.Equals(r[0], result));
        } // func TestConstant
Пример #4
0
        public static LuaResult Compile(
            StaticMetaTables staticTables,
            string source,
            dynamic globals = null,
            string name = null)
        {
            var result = new LuaResult();
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                var stream = new ANTLRStringStream(source);
                var lexer = new ChunkLexer(stream);
                var tokenStream = new CommonTokenStream(lexer);
                var parser = new ChunkParser(tokenStream);

                var r = parser.chunk();
                result.Errors.AddRange(parser.Errors);

                Expression e;
                var scope = Scope.NewTopLevelScop();
                var chunk = new Chunk();
                result.Errors.AddRange(chunk.Generate(staticTables, scope, r.Tree, out e));

                var fnExp = Expression.Lambda<Func<Table, object>>(e, scope.Env.GlobalParameter);
                result.Chunk = new CompiledChunk(fnExp.Compile(), globals ?? new Table(), name);
            }
            finally
            {
                stopwatch.Stop();
                result.ElapsedTime = stopwatch.Elapsed;
                result.Success = !result.Errors.ContainsError();
            }
            return result;
        }
Пример #5
0
        /// <summary>
        /// 读取lua,并返回luaTable
        /// </summary>
        /// <param name="path"></param>
        /// <param name="encoding"></param>
        /// <param name="isReturn"></param>
        /// <returns></returns>
        public LuaTable ReadLua(string code, bool isReturn)
        {
            //lua读取
            using (Lua l = new Lua())
            {
                // 创建环境
                var g = l.CreateEnvironment();

                // 读取文件
                //  StreamReader reader = new StreamReader(path, encoding);
                LuaResult r = new LuaResult();
                try
                {
                    r = g.DoChunk(code, "test.lua");
                }
                catch (Exception)
                {
                }

                // reader.Close();
                // 如果有返回值
                if (isReturn)
                {
                    LuaTable lt = (LuaTable)r[0];
                    return(lt);
                }
                else
                {
                    LuaTable lt = g;
                    return(lt);
                }
            }
        }
 /// <summary>
 /// 读取lua,并返回luaTable
 /// </summary>
 /// <param name="path"></param>
 /// <param name="encoding"></param>
 /// <param name="isReturn"></param>
 /// <returns>LuaTable</returns>
 public static LuaTable ReadLua(string path, Encoding encoding, bool isReturn)
 {
     //lua读取
     using (var lua = new Lua())
     {
         // 创建环境
         var luaGlobalPortable = lua.CreateEnvironment();
         // 读取文件
         var streamReader = new StreamReader(path, encoding);
         var luaResult    = new LuaResult();
         try
         {
             luaResult = luaGlobalPortable.DoChunk(streamReader, "test.lua");
         }
         catch (Exception)
         {
             // ignored
         }
         streamReader.Close();
         // 如果有返回值
         if (isReturn)
         {
             var luaTable = (LuaTable)luaResult[0];
             return(luaTable);
         }
         else
         {
             LuaTable luaTable = luaGlobalPortable;
             return(luaTable);
         }
     }
 }
Пример #7
0
    private void AddHandler(string name, BaseLuaController controller, MethodInfo method)
    {
        if (!this.handlers.ContainsKey(name))
        {
            this.handlers[name] = new();
        }

        this.handlers[name].Add((luaEvent) =>
        {
            var parameters = MapParameters(luaEvent.Parameters, method);
            var result     = controller.HandleEvent(luaEvent, (values) => method.Invoke(controller, parameters));

            if (method.ReturnType == typeof(void))
            {
                return(null);
            }

            if (result is LuaResult luaResult)
            {
                return(luaResult);
            }

            return(LuaResult <object?> .Success(result));
        });

        this.luaEventService.AddEventHandler(name, HandleLuaEvent);
    }
Пример #8
0
 internal PpsLuaTask(IPpsLuaTaskParent parent, SynchronizationContext context, CancellationToken cancellationToken, LuaResult startArguments)
 {
     this.parent            = parent;
     this.cancellationToken = cancellationToken;
     // the synchronization context must not have parallelity, we enforce this with the thread id
     this.context       = context ?? new PpsLuaTaskSynchronizationContext(this);
     this.currentResult = startArguments;
 }         // ctor
Пример #9
0
 public LuaResult ExecLuaFunction(LuaManager luaManager, LuaGlobal g, string strLuaFunction, GameClient client)
 {
     lock (dictLuaCache)
     {
         LuaResult retValue = (g as dynamic)[strLuaFunction](GameManager.LuaMgr, client, /*lua.GetTable("tab")*/ null);
         return(retValue);
     }
 }
Пример #10
0
        }         // proc SetException

        private void ExecuteTask(object continueWith)
        {
            isQueuedTaskRunning = true;
            try
            {
                // check for cancel or exception
                if (!IsCanceled && !IsFaulted)
                {
                    // execute task
                    try
                    {
                        currentResult = Invoke(continueWith, currentResult.Values);
                    }
                    catch (TaskCanceledException)
                    {
                        if (!cancellationToken.IsCancellationRequested)
                        {
                            cancellationTokenSource?.Cancel();
                        }
                    }
                    catch (Exception e)
                    {
                        SetException(e);
                    }
                }
            }
            finally
            {
                isQueuedTaskRunning = false;
            }

            if (continueTasks.Count > 0 && !IsFaulted)
            {
                ExecuteOrQueueTask(continueTasks.Dequeue());
            }
            else
            {
                // call exception
                if (onExceptionTask != null)
                {
                    ExecuteOnExceptionTask();
                }

                // call finally
                if (onFinallyTask != null)
                {
                    ExecuteOnFinallyTask();
                }

                // call awaitTask
                if (onAwaitTask != null)
                {
                    ExecuteOnAwaitTask();
                }
            }
        }         // proc ExecuteTask
Пример #11
0
        } // func FormatValue

        public static void TestResult(LuaResult result, params object[] expectedResult)
        {
            if (result == null)
            {
                throw new ArgumentNullException("no result");
            }

            if (expectedResult == null || expectedResult.Length == 0) // no results expected
            {
                if (result.Values.Length == 0)
                {
                    Console.WriteLine("OK: no result == no result");
                }
                else
                {
                    Console.WriteLine("FAIL: no result != {0}", FormatValue(result[0]));
                    Assert.Fail();
                }
            }
            else
            {
                for (int i = 0; i < expectedResult.Length; i++)
                {
                    object valueResult   = result[i];
                    object valueExpected = expectedResult[i];

                    if (valueResult is double)
                    {
                        valueResult = Math.Round((double)valueResult, 3);
                    }
                    if (valueExpected is double)
                    {
                        valueExpected = Math.Round((double)valueExpected, 3);
                    }

                    if (valueResult is LuaTable && valueExpected is KeyValuePair <object, object>[])
                    {
                        TestTable((LuaTable)valueResult, (KeyValuePair <object, object>[])valueExpected);
                    }
                    else
                    {
                        bool lOk = Object.Equals(valueResult, valueExpected);
                        Console.WriteLine("{0}: {1} {2} {3}", lOk ? "OK" : "FAIL", FormatValue(valueResult), lOk ? "==" : "!=", FormatValue(valueExpected));
                        if (!lOk)
                        {
                            Assert.Fail();
                        }
                    }
                }
                if (result.Values.Length != expectedResult.Length)
                {
                    Console.WriteLine("FAIL: Result Count {0} != {1}", result.Values.Length, expectedResult.Length);
                    Assert.Fail();
                }
            }
        } // proc TestResult
Пример #12
0
        /// <summary>
        /// Runs a block of Lua code from a string.
        /// </summary>
        /// <param name="block">The code to run.</param>
        /// <param name="env">The Lua environment to run it in.</param>
        /// <returns>The script's return value, or False if an error occurred.</returns>
        public static LuaResult Run(string block, LuaGlobal env = null)
        {
            if (env == null)
            {
                env = Environment;
            }

            // Do we have this chunk cached? If so, use that version.
            var      hash          = block.GetHashCode();
            var      useCache      = false;
            LuaChunk compiledChunk = null;

            if (LuaCache.ContainsKey(hash))
            {
                compiledChunk = LuaCache[hash];
                useCache      = true;
            }
            else
            {
                // Attempt to compile and add it to the cache.
                try
                {
                    compiledChunk = IronLua.CompileChunk(block, "lol.lua", null);
                    useCache      = true;
                    LuaCache.Add(hash, compiledChunk);
                }
                catch (LuaException pax)
                {
                    //Wrap it up in a normal Exception that our custom handler can then unwrap, so we can show the context in a nice way.
                    throw new Exception("Lua parse error while trying to run this chunk:" + System.Environment.NewLine + PrepareParseError(block, pax.Line, pax.Column) + System.Environment.NewLine + pax.Message, pax);
                }
            }

            // TODO: It failed to compile? Run interpreted and hope for useful information
            LuaResult ret = null;

            try
            {
                if (useCache)
                {
                    ret = env.DoChunk(compiledChunk);
                }
                else
                {
                    ret = env.DoChunk(block, "lol.lua");
                }
            }
            catch (LuaException pax)
            {
                //Wrap it up in a normal Exception that our custom handler can then unwrap, so we can show the context in a nice way.
                throw new Exception("Lua parse error while trying to run this chunk:" + System.Environment.NewLine + PrepareParseError(block, pax.Line, pax.Column) + System.Environment.NewLine + pax.Message, pax);
            }
            return(ret);
        }
Пример #13
0
        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            try
            {
                var requestingAssembly = args.RequestingAssembly;
                var requestedAssembly  = new AssemblyName(args.Name);

                // ①カレントディレクトリの.dllのファイル名部分だけを指定している場合(.NETの既存ライブラリと同じ書き方。
                // もしくは、C#のusingで読み込めなかった場合もこれに該当する
                String currentmacrodirectory = (String)Hidemaru.Macro.Var["currentmacrodirectory"];
                var    targetfullpath        = currentmacrodirectory + @"\" + requestedAssembly.Name + ".dll";
                if (System.IO.File.Exists(targetfullpath))
                {
                    return(Assembly.LoadFile(targetfullpath));
                }

                // ②そのようなフルパスが指定されている場合(フルパスを指定した書き方)
                targetfullpath = requestedAssembly.Name;
                if (System.IO.File.Exists(targetfullpath))
                {
                    // そのファイルのディレクトリ
                    var normalizedfullpath = System.IO.Path.GetFullPath(targetfullpath);
                    var targetdirectory    = System.IO.Path.GetDirectoryName(normalizedfullpath);

                    return(Assembly.LoadFile(targetfullpath));
                }

                // ③パスが特別に登録されている
                // 何型かはわからないが… 呼び出し側は list[x]形式で呼び出せるものだと考えた。
                LuaResult r        = g.DoChunk("return package.path", "test.lua");
                String    asm_path = r.ToString();

                if (asm_path != null)
                {
                    foreach (var dir in asm_path.Split(';'))
                    {
                        targetfullpath = dir + @"\" + requestedAssembly.Name + ".dll";
                        Hidemaru.debuginfo(targetfullpath);
                        if (System.IO.File.Exists(targetfullpath))
                        {
                            return(Assembly.LoadFile(targetfullpath));
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return(null);
        }
Пример #14
0
        }         // func CreateField

        private bool TryResolveFieldCreator(IPpsDataFieldReadOnlyProperties properties, out LuaWpfCreator[] creator)
        {
            if (String.IsNullOrEmpty(properties.UseFieldFactory))
            {
                creator = null;
                return(false);
            }

            // resolve complex fieldinformation within the Environment
            // the member must be registered within the table.
            var result = new LuaResult(CallMemberDirect(properties.UseFieldFactory, new object[] { properties }, rawGet: true, throwExceptions: true, ignoreNilFunction: true));

            if (result.Count == 0)
            {
                creator = null;
                return(false);
            }
            else if (result.Count == 1 && result[0] is LuaWpfCreator r)
            {
                creator = new LuaWpfCreator[] { r };
                return(true);
            }
            else if (result.Count == 1 && result[0] is LuaWpfCreator[] ra)
            {
                creator = ra;
                return(true);
            }
            else if (result.Count > 1)
            {
                var wpfControls = new LuaWpfCreator[result.Count];
                for (var i = 0; i < wpfControls.Length; i++)
                {
                    if (result[i] is LuaWpfCreator t)
                    {
                        wpfControls[i] = t;
                    }
                    else
                    {
                        throw new ArgumentNullException(properties.UseFieldFactory, "Return type must be a control creator.");
                    }
                }
                creator = wpfControls;
                return(true);
            }
            else
            {
                throw new ArgumentNullException(properties.UseFieldFactory, "Return type must be a control creator.");
            }
        }         // func TryResolveFieldCreator
Пример #15
0
        public static string ResultToMessage(LuaResult r)
        {
            switch (r)
            {
            case LuaResult.ErrErr: return("Error in error handler");

            case LuaResult.ErrMem: return("Out of memory");

            case LuaResult.ErrRun: return("Runtime error");

            case LuaResult.ErrSyntax: return("Syntax error");

            default: return("?");
            }
        }
Пример #16
0
    } // func FormatValue

    public static void TestResult(LuaResult result, params object[] expectedResult)
    {
      if(result == null)
        throw new ArgumentNullException("no result");

      if (expectedResult == null || expectedResult.Length == 0) // no results expected
      {
        if (result.Values.Length == 0)
        {
          Console.WriteLine("OK: no result == no result");
        }
        else
        {
          Console.WriteLine("FAIL: no result != {0}", FormatValue(result[0]));
          Assert.Fail();
        }
      }
      else
      {
        for (int i = 0; i < expectedResult.Length; i++)
        {
          object valueResult = result[i];
          object valueExpected = expectedResult[i];

          if (valueResult is double)
            valueResult = Math.Round((double)valueResult, 3);
          if (valueExpected is double)
            valueExpected = Math.Round((double)valueExpected, 3);

          if (valueResult is LuaTable && valueExpected is KeyValuePair<object, object>[])
            TestTable((LuaTable)valueResult, (KeyValuePair<object, object>[])valueExpected);
          else
          {
            bool lOk = Object.Equals(valueResult, valueExpected);
            Console.WriteLine("{0}: {1} {2} {3}", lOk ? "OK" : "FAIL", FormatValue(valueResult), lOk ? "==" : "!=", FormatValue(valueExpected));
            if (!lOk)
              Assert.Fail();
          }
        }
        if (result.Values.Length != expectedResult.Length)
        {
          Console.WriteLine("FAIL: Result Count {0} != {1}", result.Values.Length, expectedResult.Length);
          Assert.Fail();
        }
      }
    } // proc TestResult
Пример #17
0
        public void CodePlexExample1()
        {
            using (Lua l = new Lua())
            {
                var     g  = l.CreateEnvironment();
                dynamic dg = g;

                LuaResult r = g.DoChunk("return a + b", "test.lua",
                                        new KeyValuePair <string, object>("a", 2),
                                        new KeyValuePair <string, object>("b", 4));

                Console.WriteLine(r[0]);

                dynamic dr = dg.dochunk("return a + b", "test.lua", "a", 2, "b", 4);
                Console.WriteLine((int)dr);
            }
        }
Пример #18
0
        internal static ScriptIdentity?GetIdentity(LuaResult thread)
        {
            ScriptIdentity identity;

            var th = (LuaThread)thread.Values[0];

            if (th == null)
            {
                return(null);
            }

            if (_threadIdentities.TryGetValue(th, out identity))
            {
                return(identity);
            }

            return(null);
        }
Пример #19
0
        public bool Execute(SessionHandler oSessionHndlr)
        {
            if (oSessionHndlr.LuaLogger == null)
            {
                //oSessionHndlr.LuaLogger = new CLogger(oSessionHndlr.HostName, string.Empty, oSessionHndlr.ThreadIndex, true);
            }
            //oSessionHndlr.LuaLogger.WriteLogInfo("Script Execution started");
            bool result = false;

            try
            {
                //oSessionHndlr.LuaLogger.WriteLogInfo("Getting list of lua script files");

                string[] scriptFiles = System.IO.Directory.GetFiles(@LUA_SCRIPT_LOCATION, ConstantVariables.LUA_SCRIPTS_SEARCH_PATTERN);
                if (scriptFiles.Length == 0)
                {
                    //oSessionHndlr.LuaLogger.WriteLogInfo("No ScriptFiles Found.So, Script files found");
                    return(false);
                }

                var proxyAPI = new ProxyServiceAPI(oSessionHndlr);
                foreach (var scriptFile in scriptFiles)
                {
                    string currentScriptFile = Path.GetFileNameWithoutExtension(scriptFile);
                    //oSessionHndlr.LuaLogger.WriteLogInfo("Getting  lua script filename:" + currentScriptFile);

                    try
                    {
                        LuaResult lr = m_LuaGlobal.DoChunk(File.ReadAllText(String.Format(scriptFile, 1)),
                                                           currentScriptFile, new KeyValuePair <string, object>(PROXY_SERVICE_API_OBJECT_NAME, proxyAPI));
                    }
                    catch (Exception ex)
                    {
                        //oSessionHndlr.LuaLogger.WriteLogException("Script Name:" + currentScriptFile + ex.Message + Environment.NewLine + ex.StackTrace);
                    }
                }
            }
            catch (Exception ex)
            {
                //AnalyzerManager.Logger.Error(ex);
                Debug.Write(ex.Message + " " + ex.StackTrace);
            }
            return(result);
        }
Пример #20
0
 /// <summary>МЕТОД Запускаем Событие OnBeforeSave, перед cохранением формы</summary>
 public bool MET_OnBeforeSave()
 {
     if (!PROP_OnBeforeSave)
     {
         return(true);
     }
     try
     {
         LuaResult _LuaResult = PRI_Env.OnBeforeSave();
         return((bool)_LuaResult[0]);
     }
     catch (Exception e)
     {
         MyGlo.PUB_Logger.Error(e, $"Ошибка Lua в поле с VarId {PUB_Pole.PROP_VarId}," +
                                $" шаблона {PUB_Pole.PROP_FormShablon.PROP_Docum.PROP_ListShablon.PROP_Cod}," +
                                $"\n таблицы {PUB_Pole.PROP_FormShablon.PROP_TipProtokol.PROP_Shablon}");
         return(true);
     }
 }
Пример #21
0
        public static void parallel(string code, int count)
        {
            var watch = new Stopwatch();

            watch.Start();

            var       lua = new Lua();
            LuaGlobal env = lua.CreateEnvironment();
            LuaResult cc  = env.DoChunk(code, "test.lua");
            dynamic   en  = env;

            Parallel.For(0, count, x =>
            {
                string data = en.exec(10);
            });

            watch.Stop();
            Console.WriteLine("time=>{0}", watch.ElapsedMilliseconds);
        }
Пример #22
0
        private static void LinqTest2()
        {
            LuaType.RegisterTypeExtension(typeof(Enumerable));             // generic geht nicht
            List <int> lst = new List <int>();

            lst.Add(1);
            lst.Add(2);
            lst.Add(3);
            using (Lua l = new Lua())
            {
                var g = l.CreateEnvironment();

                LuaResult r = g.DoChunk(String.Join(Environment.NewLine,
                                                    "return a.Select(function (c) return c; end).ToArray();"
                                                    ), new KeyValuePair <string, object>("a", lst));

                Console.WriteLine(r[0].ToString());
            }
        }
Пример #23
0
        public static LuaMap merge(LuaMap map1, LuaMap map2, Func <object, object, LuaResult> func)
        {
            Dictionary <object, object> map = new Dictionary <object, object>(map1.map);

            foreach (KeyValuePair <object, object> entry in map2.map)
            {
                if (func != null)
                {
                    object value;
                    if (map.TryGetValue(entry.Key, out value))
                    {
                        LuaResult res = func(value, entry.Value);
                        map[entry.Key] = res[0];
                        continue;
                    }
                }
                map[entry.Key] = entry.Value;
            }
            return(new LuaMap(map));
        }
Пример #24
0
        private static void innerTemploadfile(string code, int count)
        {
            var watch = new Stopwatch();

            watch.Start();

            using (var lua = new Lua())
            {
                for (int i = 0; i < count; i++)
                {
                    LuaGlobal env  = lua.CreateEnvironment();
                    LuaResult cc   = env.DoChunk(code, "test.lua");
                    dynamic   en   = env;
                    string    data = en.exec(1);
                }
            }

            watch.Stop();
            Console.WriteLine("time=>{0}", watch.ElapsedMilliseconds);
        }
Пример #25
0
        public static string SerializeArguments(LuaResult args)
        {
            if (args == null)
            {
                return("\xC0");
            }

            var table = new LuaTable();

            for (int i = 0; i < args.Count; i++)
            {
                table[i] = args[i];
            }

            var luaEnvironment = ScriptEnvironment.CurrentEnvironment.LuaEnvironment;
            var packer         = (Func <LuaTable, string>)((LuaTable)luaEnvironment["msgpack"])["pack"];

            var str = packer(table);

            return(str);
        }
Пример #26
0
        public static string SerializeArguments(LuaResult args)
        {
            if (args == null)
            {
                return "\xC0";
            }

            var table = new LuaTable();

            for (int i = 0; i < args.Count; i++)
            {
                table[i] = args[i];
            }

            var luaEnvironment = ScriptEnvironment.CurrentEnvironment.LuaEnvironment;
            var packer = (Func<LuaTable, string>)((LuaTable)luaEnvironment["msgpack"])["pack"];

            var str = packer(table);

            return str;
        }
Пример #27
0
            internal override bool TryFulfill()
            {
                var compileOptions = new CustomCompileOptions(Script)
                {
                    DebugEngine = LuaSettings.DebugEngineEnabled ? (Script.Debugger?.NeoDebugger ?? (Script.Debugger = new ScriptDebugger(Script)).NeoDebugger) : null
                };

                var del = (Action) delegate
                {
                    try
                    {
                        if (LuaSettings.AreScriptStartsReported)
                        {
                            Script.Print($"Script started. ({Script.GetFullName()})", LogLevel.Trace);
                        }
                        Script.IsRunning = true;
                        CurrentScript    = Script;

                        var chunk     = Lua.CompileChunk(new StringReader(Script.Source), Script.InstanceId, compileOptions, new KeyValuePair <string, Type>("args", typeof(LuaTable)));
                        var argsTable = Args.ToLuaTable();

                        Result           = Script.LuaGlobal.DoChunk(chunk, argsTable);
                        Script.IsRunning = false;
                    }
                    catch (Exception e)
                    {
                        HandleException(e, Script.InstanceId);
                        Result = null;
                    }
                };

                var thread = new LuaThread(del);

                _threadIdentities[thread] = Script.Identity;

                Script.LuaThread = thread;
                ResumeThread(thread);

                return(true);
            }
Пример #28
0
    } // ctor

    /// <summary>Gibt die Daten frei</summary>
    public void Dispose()
    {
      currentArguments = null;
      currentArguments = null;
			if (taskCancelExecute != null)
			{
				if (!taskCancelExecute.IsCancellationRequested)
					taskCancelExecute.Cancel();
				taskCancelExecute.Dispose();
				taskCancelExecute = null;
			}
      if (evYield != null)
      {
        evYield.Dispose();
        evYield = null;
      }
      if (evResume != null)
      {
        evResume.Set();
        evResume.Dispose();
        evResume = null;
      }
    } // proc Dispose
Пример #29
0
        }         // ctor

        internal PpsLuaTask(IPpsLuaTaskParent parent, SynchronizationContext context, CancellationTokenSource cancellationTokenSource, LuaResult startArguments)
            : this(parent, context, cancellationTokenSource?.Token ?? CancellationToken.None, startArguments)
        {
            this.cancellationTokenSource = cancellationTokenSource;
        }         // ctor
Пример #30
0
        public string EvaluateLua(string expression)
        {
            bool unfreeze = false;

            if (this.CurrentState == DebugState.Running)
            {
                unfreeze = true;
                if (!GameLoopHook.PauseGame())
                {
                    return("Error: Game is busy!");
                }
            }
            this.DebugEngine.RemoveHook();

            string asStatement = expression;

            expression = "return " + expression;

            string    result = "";
            LuaResult err    = BBLua.luaL_loadbuffer(this.L, expression, expression.Length, "from console");

            if (err == LuaResult.OK)
            {
                int stackTop = BBLua.lua_gettop(this.L);
                err = BBLua.lua_pcall(this.L, 0, -1, 0);
                int nResults = 1 + BBLua.lua_gettop(this.L) - stackTop;

                if (nResults == 1)
                {
                    result = TosToString();
                }
                else if (nResults > 1)
                {
                    string[] results = new string[nResults];
                    do
                    {
                        nResults--;
                        results[nResults] = TosToString(true);
                    } while (nResults != 0);

                    result = "(" + string.Join(", ", results) + ")";
                }
            }
            else
            {
                string parseErrExpr = TosToString();

                err = BBLua.luaL_loadbuffer(this.L, asStatement, asStatement.Length, "from console");
                if (err == LuaResult.OK)
                {
                    err = BBLua.lua_pcall(this.L, 0, 0, 0); //statement -> no return values
                }
                if (err != LuaResult.OK)
                {
                    result = TosToString();
                }
            }

            this.DebugEngine.SetHook();
            if (unfreeze)
            {
                GameLoopHook.ResumeGame();
            }

            return(result);
        }
Пример #31
0
    public static IntPtr DoString(String expression, String inAction = "DoString")
    {
        if (CreateScope() == (IntPtr)0)
        {
            return((IntPtr)0);
        }

        try
        {
            LuaResult r = g.DoChunk(expression, "test.lua");
            return((IntPtr)1);
        }
        catch (LuaParseException e)
        {
            OutputDebugStream(e.GetType().Name + ":");
            OutputDebugStream("lineno:" + e.Line + " in " + inAction);

            // エラーの行番号
            int ix = e.Line - 1;

            // ソースを改行で分割
            string[] list = expression.Split('\n');

            // 該当行をデバッグモニターへと出力
            if (0 <= ix && ix < list.Length)
            {
                OutputDebugStream(list[ix]);
            }
        }
        catch (LuaRuntimeException e)
        {
            OutputDebugStream(e.GetType().Name + ":");
            OutputDebugStream("lineno:" + e.Line + " in " + inAction);

            // エラーの行番号
            int ix = e.Line - 1;

            // ソースを改行で分割
            string[] list = expression.Split('\n');

            // 該当行をデバッグモニターへと出力
            if (0 <= ix && ix < list.Length)
            {
                OutputDebugStream(list[ix]);
            }
        }
        catch (LuaException e)
        {
            OutputDebugStream(e.GetType().Name + ":");
            OutputDebugStream("lineno:" + e.Line + " in " + inAction);

            // エラーの行番号
            int ix = e.Line - 1;

            // ソースを改行で分割
            string[] list = expression.Split('\n');

            // 該当行をデバッグモニターへと出力
            if (0 <= ix && ix < list.Length)
            {
                OutputDebugStream(list[ix]);
            }
        }
        catch (Exception e)
        {
            OutputDebugStream(e.GetType().Name + ":");
            OutputDebugStream(e.Message);
            OutputDebugStream(e.StackTrace);
        }
        return((IntPtr)0);
    }
Пример #32
0
        public override bool Cook(string luaPath, LuaGlobal environment, string outputDirectory, string intermediateDirectory, out string producedFile, out string error)
        {
            error        = "";
            producedFile = "";
            string shaderPath = GetShaderPath(luaPath, environment);

            // Figure out which shader type we're trying to compile
            ShaderType shaderType = GetShaderType(shaderPath, environment);

            if (shaderType == ShaderType.Unknown)
            {
                error = "Shader type was unknown, either use one of the following file extensions: ";

                bool first = true;
                foreach (KeyValuePair <string, ShaderType> validShaderType in validShaderTypes)
                {
                    if (!first)
                    {
                        error += ", ";
                    }
                    else
                    {
                        first = false;
                    }

                    error += validShaderType.Key + ".hlsl";
                }
                error += "\n OR set shaderType in the .lua file";

                return(false);
            }

            // Try to get all settings from .lua file or acceptable defaults
            ShaderCompileSettings compileSettings = new ShaderCompileSettings();

            compileSettings.shaderPath            = shaderPath;
            compileSettings.outputDirectory       = Path.Combine(outputDirectory, "shaders");
            compileSettings.intermediateDirectory = intermediateDirectory;

            compileSettings.entryPoint   = Env.TryGetDefault <string>(environment, "entryPoint", "main");
            compileSettings.optimization = Env.TryGetDefault <string>(environment, "optimization", "Od");
            compileSettings.profile      = GetShaderProfile(shaderType, environment);
            compileSettings.debug        = Env.TryGetDefault <bool>(environment, "debug", true);
            compileSettings.outputFile   = GetShaderOutputFileName(shaderPath, environment, shaderType);
            compileSettings.defines      = Env.TryGetArrayDefault <string>(environment, "defines", new string[0]);

            if (environment.ContainsMember("OnCompile"))
            {
                string producedFileStr = "";

                // Add the compileShader function to the lua environment
                dynamic dynamicEnvironment = environment;
                dynamicEnvironment.compileShader = new Func <LuaTable, bool>((compileSettingsTable) =>
                {
                    ShaderCompileSettings settings = ShaderCompileSettings.FromLuaTable(compileSettingsTable);
                    producedFileStr = Path.Combine(settings.outputDirectory, settings.outputFile);
                    return(CompileShader(settings));
                });

                // Lets call OnCompile to allow the lua file to handle mutations on its own
                LuaTable  table  = compileSettings.ToLuaTable();
                LuaResult result = environment.CallMember("OnCompile", table);

                // Remove the compileShader function
                dynamicEnvironment.compileShader = null;

                if (result.Count != 1)
                {
                    Debug.Fail("[SHADER COOKER]: If a Lua file overrides OnCompile it has to return a bool to specify if it succeeded");
                }
                producedFile = producedFileStr;
                return((bool)result[0]);
            }
            else
            {
                producedFile = Path.Combine(compileSettings.outputDirectory, compileSettings.outputFile);
                return(CompileShader(compileSettings));
            }
        }
Пример #33
0
 internal LuaTuple(T1 arg1 = default(T1))
 {
     _result = new LuaResult(arg1);
 }
Пример #34
0
    } // func Yield

    #endregion

    #region -- ExecuteDelegate --------------------------------------------------------

    private void ExecuteDelegate()
    {
      evResume = new ManualResetEventSlim(false);

			Task.Yield(); // force background thread

      // add this thread to the thread-pool
      lock (luaThreads)
        luaThreads.Add(this);

			try
			{
				yield(new LuaResult(Lua.RtInvoke(target, currentArguments.Values)));
			}
			finally
			{
				// remove the thread from the pool
				lock (luaThreads)
					luaThreads.Remove(this);

				taskExecute = null;
				taskCancelExecute.Dispose();
				taskCancelExecute = null;

				// dispose the events
				currentYield = LuaResult.Empty;
				evResume.Dispose();
				evResume = null;
				evYield.Set();
			}
    } // proc ExecuteDelegate
Пример #35
0
        }         // func ParseArgument

        private static void RunScript(Func <string> code, string sName)
        {
            try
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();

                // compile chunk
                LuaChunk c = lua.CompileChunk(code(), sName, new LuaCompileOptions()
                {
                });

                string sCompileTime = String.Format("{0:N0} ms", sw.ElapsedMilliseconds);
                sw.Reset();
                sw.Start();

                // run chunk
                LuaResult r        = global.DoChunk(c);
                string    sRunTime = String.Format("{0:N0} ms", sw.ElapsedMilliseconds);

                string sSize;
                if (c.Size < 0)
                {
                    sSize = "unknown";
                }
                else if (c.Size == 0)
                {
                    sSize = String.Empty;
                }
                else
                {
                    sSize = c.Size.ToString("N0") + " byte";
                }

                // start with a new line
                if (Console.CursorLeft > 0)
                {
                    Console.WriteLine();
                }

                // print result
                if (r.Count > 0)
                {
                    for (int i = 0; i < r.Count; i++)
                    {
                        WriteVariable(i, r[i]);
                    }
                }

                // print summary
                const string csCompile = "==> compile: ";
                const string csRuntime = " run: ";

                Console.CursorLeft = Console.WindowWidth - csCompile.Length - (sSize.Length > 0 ? sSize.Length + 3 : 0) - sCompileTime.Length - csRuntime.Length - sRunTime.Length - 1;
                WriteText(ConsoleColor.DarkGreen, csCompile);
                WriteText(ConsoleColor.Green, sCompileTime);
                if (sSize.Length > 0)
                {
                    WriteText(ConsoleColor.DarkGreen, " [");
                    WriteText(ConsoleColor.Green, sSize);
                    WriteText(ConsoleColor.DarkGreen, "]");
                }
                WriteText(ConsoleColor.DarkGreen, csRuntime);
                WriteText(ConsoleColor.Green, sRunTime);
                Console.WriteLine();
            }
            catch (LuaParseException e)
            {
                WriteText(ConsoleColor.DarkRed, String.Format("Parse error at line {0:N0} (column: {1:N0}):", e.Line, e.Column));
                Console.WriteLine();
                WriteText(ConsoleColor.DarkRed, "  " + e.Message);
                Console.WriteLine();
            }
            catch (Exception e)
            {
                Exception ex = e is TargetInvocationException ? e.InnerException : e;
                WriteException(ex);
            }
        } // proc RunScript