Exemplo n.º 1
0
        private ShaderType GetShaderType(string shaderPath, LuaGlobal environment)
        {
            // First try getting shader type from filename
            foreach (KeyValuePair <string, ShaderType> validShaderType in validShaderTypes)
            {
                string validExtension = validShaderType.Key + ".hlsl";

                if (shaderPath.EndsWith(validExtension))
                {
                    return(validShaderType.Value);
                }
            }

            // If it didnt work, check the environment for a defined shader type
            string shaderTypeStr;

            if (Env.TryGet <string>(environment, "shaderType", out shaderTypeStr))
            {
                foreach (KeyValuePair <string, ShaderType> validShaderType in validShaderTypes)
                {
                    if (shaderTypeStr == validShaderType.Key)
                    {
                        return(validShaderType.Value);
                    }
                }
            }

            // Otherwise we have no idea what shadertype this is...
            return(ShaderType.Unknown);
        }
        private void ExtendLuaEnvironment(LuaGlobal g)
        {
            g.RegisterPackage("os", typeof(OperationSystemPackage));
            g.RegisterPackage("log", typeof(ConsolePackage));

            foreach (var package in _userProvidedPackages)
            {
                g.RegisterPackage(package.Key, package.Value);
            }

            // extension methods need to be registered separately through RegisterTypeExtension call)
            foreach (var extensionClass in _userProvidedExtensionMethodClasses)
            {
                LuaType.RegisterTypeExtension(extensionClass);
            }

            // tables can be registered directly
            dynamic dg = g;

            foreach (var pair in _userProvidedTables)
            {
                dg[pair.Key] = pair.Value;
            }

            // delegates need to be registered with the LuaGlobal
            foreach (var pair in _userProvidedDelegate)
            {
                g.DefineFunction(pair.Key, pair.Value);
            }
        }
 private void AddUserDefinedGlobals(LuaGlobal g)
 {
     foreach (var global in _userProvidedGlobals)
     {
         g[global.Key] = global.Value;
     }
 }
Exemplo n.º 4
0
        private void DoScript(Lua l, LuaGlobal g, string sScript)
        {
            Type type = typeof(RunLuaTests);

            using (Stream src = type.Assembly.GetManifestResourceStream(type, "CompTests." + sScript))
                using (StreamReader sr = new StreamReader(src))
                {
                    Console.WriteLine();
                    Console.WriteLine(new string('=', 60));
                    Console.WriteLine("= " + sScript);
                    Console.WriteLine();
                    try
                    {
                        g.DoChunk(l.CompileChunk(sr, sScript, Lua.StackTraceCompileOptions));
                    }
                    catch (Exception e)
                    {
                        if (e is LuaException)
                        {
                            Console.WriteLine("Line: {0}, Column: {1}", ((LuaException)e).Line, ((LuaException)e).Column);
                        }
                        Console.WriteLine("StackTrace:");
                        Console.WriteLine(LuaExceptionData.GetData(e).StackTrace);
                        throw;
                    }
                }
        }
Exemplo n.º 5
0
 public LazynetLua()
 {
     using (Lua l = new Lua())
     {
         this.G = l.CreateEnvironment();
     }
 }
Exemplo n.º 6
0
    public static IntPtr CreateScope()
    {
        // まだエンジンが作られていなければ
        if (l == null || g == null)
        {
            try
            {
                //エンジン作成
                l = new Lua();
                g = l.CreateEnvironment();

                hm = new Hidemaru();
                g.RegisterPackage("hm", typeof(Hidemaru));
                dpr = new DllPathResolver();
                // アセンブリのローダのショートカット
                g["load_assembly"] = new Func <String, Assembly>(asmname => System.Reflection.Assembly.Load(asmname));

                return((IntPtr)1);
            }
            catch (Exception e)
            {
                OutputDebugStream(e.Message);
                return((IntPtr)0);
            }
        }
        return((IntPtr)1);
    }
Exemplo n.º 7
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);
     }
 }
Exemplo n.º 8
0
        public void TestMember10()
        {
            var g = new LuaGlobal(new Lua());

            g["a"] = 1;
            g.Members.Clear();

            TestResult(new LuaResult(g["a"]), new object[] { null });
        }
        public LuaEngine()
        {
            this._script = "";

            _lua            = new Lua();
            _luaEnvironment = _lua.CreateEnvironment();

            this.AddVariable("TCAdminFolder", Path.GetFullPath(Path.Combine(Path.Combine(Utility.GetSharedPath(), ".."), "..")));
            this.AddVariable("Script", this);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 初始化Lua运行环境
        /// </summary>
        public void InitLuaEnv()
        {
            gEnv = lua.CreateEnvironment();

            // 每100秒对其中一个字典进行检测
            timerCheckDict          = new Timer(100 * 1000);
            timerCheckDict.Elapsed += new ElapsedEventHandler(CheckDictLuaInfo);
            timerCheckDict.Interval = 100 * 1000;
            timerCheckDict.Enabled  = true;
        }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
0
        string GetShaderPath(string luaPath, LuaGlobal environment)
        {
            string shaderPath = GetAssetPath(luaPath);

            string shaderFile = "";

            if (Env.TryGet <string>(environment, "shaderFile", out shaderFile))
            {
                shaderPath = Path.Combine(Path.GetDirectoryName(luaPath), shaderFile);
            }
            return(shaderPath);
        }
Exemplo n.º 13
0
        string GetMaterialPath(string luaPath, LuaGlobal environment)
        {
            string xmlPath = GetAssetPath(luaPath);

            string xmlFile = "";

            if (Env.TryGet <string>(environment, "material", out xmlFile))
            {
                xmlPath = Path.Combine(Path.GetDirectoryName(luaPath), xmlFile);
            }
            return(xmlPath);
        }
Exemplo n.º 14
0
        private static void TestDynamic()
        {
            var lua    = new Lua();
            var global = new LuaGlobal(lua)
            {
                ["workspace"] = new DynData()
            };

            var r = global.DoChunk("return workspace.Part", "Test.lua");

            Console.WriteLine(r.ToString());
        }
Exemplo n.º 15
0
        public ScriptEngine(IInterfaceCommands uInterfaceCommands, Game game, string[] paths)
        {
            _scriptPaths = paths.ToList();
            _scriptPaths.Add(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "Scripts");
            _lua         = new Lua();
            _environment = _lua.CreateEnvironment();
            dynamic dg = _environment;

            _log = new StringBuilder();
            _log.AppendLine(_environment.Version);
            dg.print = new Action <string>(s => _log.AppendLine(s));
            dg.civ   = new CivScripts(uInterfaceCommands, _log, game);
        }
Exemplo n.º 16
0
        public override bool CanCook(string luaPath, LuaGlobal environment, out string error)
        {
            error = "";
            string assetPath = GetAssetPath(luaPath);

            if (!assetPath.EndsWith(".bmp"))
            {
                error = "We only convert .bmp files";
                return(false);
            }

            return(File.Exists(assetPath));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Runs a block of Lua code from a file, which may be archived.
        /// </summary>
        /// <param name="name">The name of the file with 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 RunFile(string name, LuaGlobal env = null)
        {
            var ret   = Run(Mix.GetString(name), env);
            var files = Mix.GetFilesWithPattern("*-" + name);

            if (files.Length > 0)
            {
                foreach (var extra in files)
                {
                    ret = Run(Mix.GetString(extra), env);
                }
            }
            return(ret);
        }
Exemplo n.º 18
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             env = null;
             _engine.Dispose();
         }
         // TODO: 释放未托管的资源(未托管的对象)并重写终结器
         // TODO: 将大型字段设置为 null
         disposedValue = true;
     }
 }
Exemplo n.º 19
0
        public override void RegisterFunctions(LuaGlobal environment)
        {
            mutations = new Dictionary <string, string>();
            dynamic dynamicEnvironment = environment;

            dynamicEnvironment.setMutation = new Action <string, object>((mutationToken, value) =>
            {
                if (mutations.ContainsKey(mutationToken))
                {
                    mutations[mutationToken] = value.ToString();
                }
                else
                {
                    mutations.Add(mutationToken, value.ToString());
                }
            });
        }
Exemplo n.º 20
0
        string GetShaderProfile(ShaderType shaderType, LuaGlobal environment)
        {
            string profile = "";

            if (!Env.TryGet <string>(environment, "profile", out profile))
            {
                foreach (KeyValuePair <string, ShaderType> validShaderType in validShaderTypes)
                {
                    if (shaderType == validShaderType.Value)
                    {
                        profile = validShaderType.Key + "_6_5";
                        break;
                    }
                }
            }
            Debug.Assert(profile != ""); // We already checked for this, but let's verify to avoid future mistakes

            return(profile);
        }
Exemplo n.º 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);
        }
Exemplo n.º 22
0
        public override bool CanCook(string luaPath, LuaGlobal environment, out string error)
        {
            error = "";
            string shaderPath = GetShaderPath(luaPath, environment);

            if (!File.Exists(shaderPath))
            {
                error = "Asset does not exist";
                return(false);
            }

            if (!shaderPath.EndsWith(".hlsl"))
            {
                error = "We only convert .hlsl shader files";
                return(false);
            }

            return(true);
        }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
0
        string GetShaderOutputFileName(string shaderPath, LuaGlobal environment, ShaderType shaderType)
        {
            string name = Path.GetFileName(shaderPath) + ".cso";

            string overrideName = "";

            if (Env.TryGet <string>(environment, "outputFile", out overrideName))
            {
                name = overrideName;
                foreach (KeyValuePair <string, ShaderType> validShaderType in validShaderTypes)
                {
                    if (shaderType == validShaderType.Value)
                    {
                        name = Path.ChangeExtension(name, validShaderType.Key + ".cso");
                        break;
                    }
                }
            }
            return(name);
        }
        /// <summary>
        /// Runs lua files that are 'referenced' as a member of lua tables, recursively.
        /// </summary>
        /// <param name="lua">The lua context to run the scripts in.</param>
        /// <param name="g">The global lua table.</param>
        /// <param name="table">The current lua table to search for lua links.</param>
        private void RunChildLuaScripts(Lua lua, ref LuaGlobal g, LuaTable table)
        {
            var childrenWithLuaScripts =
                table.Values.Where(val => val.Value is string filename && filename.EndsWith(".lua"));

            foreach (var pair in childrenWithLuaScripts)
            {
                var filename = pair.Value.ToString();
                if (File.Exists(filename))
                {
                    try
                    {
                        var chunk = lua.CompileChunk(filename, new LuaCompileOptions()
                        {
                            DebugEngine = new LuaDebugger()
                        });
                        g.DoChunk(chunk);
                    }
                    catch (LuaDebuggerException e)
                    {
                        Console.WriteLine(e);
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"Error while calling a child lua script from table {table} - script {filename}, line {e.LastFrameLine}");
                        Console.ForegroundColor = ConsoleColor.White;
                        throw;
                    }
                }
            }

            if (table.Members.Any())
            {
                foreach (var member in table.Members)
                {
                    var memberTable = member.Value as LuaTable;
                    if (memberTable != null)
                    {
                        RunChildLuaScripts(lua, ref g, memberTable);
                    }
                }
            }
        }
Exemplo n.º 26
0
        public override bool CanCook(string luaPath, LuaGlobal environment, out string error)
        {
            error = "";

            if (!luaPath.EndsWith(".material.lua"))
            {
                error = "We only convert .material.lua files";
                return(false);
            }

            string materialPath = GetMaterialPath(luaPath, environment);

            if (!File.Exists(materialPath))
            {
                error = materialPath + " does not exist!";
                return(false);
            }


            return(true);
        }
Exemplo n.º 27
0
        public override void Load(string rawUrl, string sheetName, Stream stream)
        {
            RawUrl     = rawUrl;
            _env       = LuaManager.CreateEnvironment();
            _dataTable = (LuaTable)_env.DoChunk(new StreamReader(stream, Encoding.UTF8), rawUrl)[0];

            if (!string.IsNullOrEmpty(sheetName))
            {
                if (sheetName.StartsWith("*"))
                {
                    sheetName = sheetName.Substring(1);
                }
                if (!string.IsNullOrEmpty(sheetName))
                {
                    foreach (var subField in sheetName.Split('.'))
                    {
                        _dataTable = (LuaTable)_dataTable[subField];
                    }
                }
            }
        }
Exemplo n.º 28
0
        private static void Vector3Test()
        {
            string luaScript = @"
local Vector3 = clr.NeoTest1.Vector3
local v1 = Vector3(1, 1, 1)
print(v1)
local v2 = Vector3(v1.X, v1.Y, v1.Z)
print(v2)
";

            using (Lua lua = new Lua())
            {
                LuaGlobal lg = lua.CreateEnvironment();
                try
                {
                    lg.DoChunk(luaScript, "dummy.lua");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
            }
        }
        public LuaInstance()
        {
            lua      = new Lua();
            packages = new HashSet <string>();

            try
            {
                global = lua.CreateEnvironment();
                global["package.path"] = LuaConfig.PackagePath;

                LuaAerospike.LoadLibrary(this);
                LuaStream.LoadLibrary(this);

                Assembly assembly = Assembly.GetExecutingAssembly();
                LoadSystemPackage(assembly, "aslib");
                LoadSystemPackage(assembly, "stream_ops");
                LoadSystemPackage(assembly, "aerospike");
            }
            catch (Exception)
            {
                lua.Dispose();
                throw;
            }
        }
Exemplo n.º 30
0
 static LuaScriptHandler()
 {
     m_Lua       = new Lua();
     m_LuaGlobal = m_Lua.CreateEnvironment();
 }