Beispiel #1
0
        public void TestJson01()
        {
            var t = new LuaTable()
            {
                ["int"]   = 1,
                [1]       = 1,
                ["float"] = 1.0,
                ["byte"]  = (byte)1,
                ["str"]   = "test",
                ["do"]    = true,
                ["t"]     = new LuaTable()
                {
                    1, 2, 3, 4
                },
                [2]  = 2,
                [3]  = 3,
                [10] = 10
            };

            var s = t.ToJson();

            Console.WriteLine(s);
            var t2 = LuaTable.FromJson(s);

            Assert.AreEqual(10, t2.Values.Count);
        }
Beispiel #2
0
        public void TestJsonDateTime()
        {
            var dt = new DateTime(2012, 4, 23, 18, 25, 43, 511, DateTimeKind.Utc);
            var t  = new LuaTable()
            {
                ["test"] = dt
            };
            var s = t.ToJson(false);

            Assert.AreEqual("{\"test\":\"2012-04-23T18:25:43.5110000Z\"}", s);
            Console.WriteLine(s);
            var t2 = LuaTable.FromJson(s);

            Assert.AreEqual(dt.ToString("o"), t2["test"]);
        }
Beispiel #3
0
        public string AddJob(int repeatCount,
                             int interval, Func <LuaTable, int> call,
                             LuaTable parameters)
        {
            string jsonString   = parameters.ToJson();
            var    luaParameter = LuaTable.FromJson(jsonString);
            var    dict         = new Dictionary <string, object>()
            {
                { "Callback", call },
                { "Parameters", luaParameter }
            };

            ILazynetTimer timer = new LazynetQuartz();
            var           task  = timer.Create <LazynetLuaJob>(repeatCount, interval, dict);

            this.TimerDict.Add(task.Result, timer);
            return(task.Result);
        }
Beispiel #4
0
 /// <summary>
 /// 字符串转序列化
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static LuaTable Deserialize(this string obj)
 {
     return(LuaTable.FromJson(obj));
 }
Beispiel #5
0
        public void TestFromJson01()
        {
            dynamic t = LuaTable.FromJson("{ \"a\":true, \"b\" : false, \"c\": 10, \"d\": 1099511627776, \"e\": \"test\", \"f\": 1.0, \"g\": 1.23, \"h\": 1e10 }");

            TestResult(new LuaResult(t.a, t.b, t.c, t.d, t.e, t.f, t.g, t.h), true, false, 10, 1099511627776L, "test", 1.0, 1.23, 1e10);
        }
        protected void LoadLuaContext(string pathToMainFile, bool loadChildrenLuaLinks, bool specificChildrenOnly, IReadOnlyCollection <string> specificChildrenKeys)
        {
            var originalDirectory = Directory.GetCurrentDirectory();

            Directory.SetCurrentDirectory(_pathToConfigFolder);

            bool success = true;

            try
            {
                using (var lua = new Lua())
                {
                    dynamic g = lua.CreateEnvironment <LuaGlobal>();

                    // add in optional helper methods etc.
                    ExtendLuaEnvironment(g);

                    int baseMemberCount = ((LuaGlobal)g).Members.Count;

                    AddUserDefinedGlobals(g);

                    // each found type has its instance created in lua context as a table - this populates the tables with default values, if any are set
                    foreach (var typeAttributePair in _typesWithAttributes)
                    {
                        var type             = typeAttributePair.Key;
                        var instance         = Activator.CreateInstance(type);
                        var attribute        = typeAttributePair.Value;
                        var keyFromAttribute = attribute.Key;

                        var json  = JsonConvert.SerializeObject(instance);
                        var table = LuaTable.FromJson(json);

                        g[keyFromAttribute] = table;
                        _settingsInstances.Add(keyFromAttribute, instance);
                    }

                    LuaChunk chunk;
                    // compile the lua chunk
                    try
                    {
                        chunk = lua.CompileChunk(_mainSettingsFileName, new LuaCompileOptions()
                        {
                            DebugEngine = new LuaDebugger()
                        });
                    }
                    catch (LuaParseException e)
                    {
                        success = false;
                        Console.WriteLine($"Exception caught when parsing the lua file at line {e.Line}, column {e.Column}, source file {e.FileName}. Exception: {e}");
                        Console.WriteLine($"Offending line: {TryToGetExceptionLineFromFile(e)}");
                        throw;
                    }

                    try
                    {
                        // actually run the chunk
                        g.dochunk(chunk);

                        // lua tables can contain 'links' to other lua scripts - user can specify if they want to find those files and run those chunks as well
                        if (loadChildrenLuaLinks)
                        {
                            var globals      = ((LuaGlobal)g).Members;
                            var addedGlobals = globals.Skip(baseMemberCount).ToList();
                            var global       = g as LuaGlobal;
                            foreach (var member in addedGlobals)
                            {
                                var table = member.Value as LuaTable;
                                if (table == null)
                                {
                                    continue;
                                }

                                if (specificChildrenOnly && specificChildrenKeys.Contains(member.Key))
                                {
                                    RunChildLuaScripts(lua, ref global, table);
                                }
                                else if (!specificChildrenOnly)
                                {
                                    RunChildLuaScripts(lua, ref global, table);
                                }
                            }
                        }
                    }
                    catch (LuaParseException e)
                    {
                        success = false;
                        Console.WriteLine($"Could not parse lua exception: {e}. File {e.FileName}, Line {e.Line}, Index {e.Index}.");
                    }
                    catch (Exception e)
                    {
                        success = false;
                        Console.WriteLine($"Exception {e}");
                        // get stack trace if possible
                        var d = LuaExceptionData.GetData(e);
                        Console.WriteLine($"StackTrace: {d.FormatStackTrace(0, false)}");
                        throw;
                    }

                    // getting actual C# object representations back from the lua tables
                    var count = _settingsInstances.Count;
                    for (int index = 0; index < count; index++)
                    {
                        var instancePair = _settingsInstances.ElementAt(index);

                        // key under which the settings section has been registered
                        var key = instancePair.Key;
                        // the table filled with data from lua
                        var dynamicTable = g[key];
                        // the type of the C# object representing the settings section (needed for deserialization)
                        var typeToCreate = _typesWithAttributes.FirstOrDefault(p => p.Value.Key == key).Key;
                        // convert table to json
                        string instanceAsJson = LuaTable.ToJson(dynamicTable);
                        // deserialize json to our type
                        //var deserializedInstance = JsonSerializer.Deserialize(instanceAsJson, typeToCreate);
                        var deserializedInstance = JsonConvert.DeserializeObject(instanceAsJson, typeToCreate);
                        // store this instance
                        _settingsInstances[key] = deserializedInstance;
                    }

                    var members = ((LuaGlobal)g).Members;
                    //var relevantMembers = members.Skip(baseMemberCount).ToList();
                    var relevantMembers = members.Skip(baseMemberCount).ToDictionary(kv => kv.Key, kv => kv.Value);

                    // cache the results in tables
                    _tableCache = new LuaTable();

                    // skip methods defined in lua from caching - two reasons for that:
                    // 1) Json generation explodes on delegates,
                    // 2) they would most likely not be safe to call after the lua context is disposed anyway
                    var scrubbed = ScrubDelegateMembersFromTable(relevantMembers);
                    foreach (var pair in scrubbed)
                    {
                        _tableCache.Add(pair.Key, pair.Value);
                    }


                    var jsonCache = _tableCache.ToJson();
                    _jsonCache = JObject.Parse(jsonCache);
                }
            }
            finally
            {
                Directory.SetCurrentDirectory(originalDirectory);
                Console.WriteLine(success ? "Settings loaded successfully" : "Problem occurred when loading settings");
            }
        }