Esempio n. 1
0
 /// <summary>
 /// Gets the namespace table for the specified namespace
 /// </summary>
 /// <param name="nspace"></param>
 /// <returns></returns>
 private LuaTable GetNamespaceTable(string nspace)
 {
     if (string.IsNullOrEmpty(nspace))
     {
         return(GetNamespaceTable("global"));
     }
     else
     {
         var nspacesplit = nspace.Split('.');
         var curtable    = LuaEnvironment["_G"] as LuaTable;
         if (curtable == null)
         {
             Interface.Oxide.LogError("_G is null!");
             return(null);
         }
         for (var i = 0; i < nspacesplit.Length; i++)
         {
             var prevtable = curtable;
             curtable = curtable?[nspacesplit[i]] as LuaTable;
             if (curtable != null)
             {
                 continue;
             }
             LuaEnvironment.NewTable("tmp");
             curtable = LuaEnvironment["tmp"] as LuaTable;
             LuaEnvironment["tmp"] = null;
             if (prevtable != null)
             {
                 prevtable[nspacesplit[i]] = curtable;
             }
         }
         return(curtable);
     }
 }
Esempio n. 2
0
        static void Main(string[] args)
        {
            LuaEnvironment env = new LuaEnvironment();
            var            Lua = LuaEnvironment.CreateScript("HelloWorld", new object());

            Lua.Start();
        }
Esempio n. 3
0
 public MessageTransmit(int id, MessageType type, LuaEnvironment luaEnv, string code)
 {
     Id     = id;
     Type   = type;
     LuaEnv = luaEnv;
     Code   = code;
 }
Esempio n. 4
0
    void Awake()
    {
        getInstance = this;

        UserData.RegisterAssembly();
        Script.DefaultOptions.DebugPrint = (s) => Debug.Log(s);
    }
Esempio n. 5
0
        /// <summary>
        /// Populates the config with default settings
        /// </summary>
        protected override void LoadDefaultConfig()
        {
            LuaEnvironment.NewTable("tmp");
            var tmp = LuaEnvironment["tmp"] as LuaTable;

            Table["Config"]       = tmp;
            LuaEnvironment["tmp"] = null;
            CallHook("LoadDefaultConfig", null);
            Utility.SetConfigFromTable(Config, tmp);
        }
Esempio n. 6
0
        /// <summary>
        /// Creates an overload selector with the specified set of methods
        /// </summary>
        /// <param name="methods"></param>
        /// <returns></returns>
        private LuaTable CreateOverloadSelector(MethodBase[] methods)
        {
            LuaEnvironment.NewTable("overloadselector");
            var tbl = LuaEnvironment["overloadselector"] as LuaTable;

            LuaEnvironment["overloadselector"] = null;
            tbl["methodarray"] = methods;
            setmetatable.Call(tbl, overloadselectormeta);
            return(tbl);
        }
Esempio n. 7
0
    private void audioPlay()
    {
        GameObject     lua           = GameObject.Find("LuaControllerAudio");
        LuaEnvironment luaEvironment = lua.GetComponent <LuaEnvironment> ();

        luaEvironment.Interpreter.Globals ["pid"] = i;
        luaEvironment.Interpreter.Globals ["animationAvailable"] = animationAvailable;
        LuaScript luascript = lua.GetComponent <LuaScript> ();

        luascript.OnExecute();
    }
Esempio n. 8
0
        public LuaScript(LuaEnvironment env, string path, object gameObject)
        {
            _Env = env;
            var envTable = env.NewTable(path, gameObject);

            _Table = envTable;

            envTable.Get("Print", out _Start);

            if (_Start == null)
            {
                _Start = _Empty;
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Called when this plugin has been removed from the specified manager
        /// </summary>
        /// <param name="manager"></param>
        public override void HandleRemovedFromManager(PluginManager manager)
        {
            // Let plugin know that it's unloading
            OnCallHook("Unload", null);

            // Remove us from the watcher
            watcher.RemoveMapping(Name);

            // Call base
            base.HandleRemovedFromManager(manager);

            Table.Dispose();
            LuaEnvironment.DeleteObject(this);
            LuaEnvironment.DoString("collectgarbage()");
        }
Esempio n. 10
0
        /// <summary>
        /// Loads a library into the specified path
        /// </summary>
        /// <param name="library"></param>
        /// <param name="path"></param>
        public void LoadLibrary(Library library, string path)
        {
            //Interface.Oxide.RootLogger.Write(LogType.Debug, "Loading library '{0}' into Lua... (path is '{1}')", library.GetType().Name, path);

            // Create the library table if it doesn't exist
            var libraryTable = LuaEnvironment[path] as LuaTable;

            if (libraryTable == null)
            {
                LuaEnvironment.NewTable(path);
                libraryTable = LuaEnvironment[path] as LuaTable;
                //Interface.Oxide.RootLogger.Write(LogType.Debug, "Library table not found, creating one... {0}", libraryTable);
            }
            else
            {
                //Interface.Oxide.RootLogger.Write(LogType.Debug, "Library table found, using it... {0}", libraryTable);
            }

            // Bind all methods
            foreach (var name in library.GetFunctionNames())
            {
                var method = library.GetFunction(name);
                LuaEnvironment.RegisterFunction($"{path}.{name}", library, method);
            }

            // Only bind properties if it's not global
            if (path != "_G")
            {
                // Create properties table
                LuaEnvironment.NewTable("tmp");
                var propertiesTable = LuaEnvironment["tmp"] as LuaTable;
                //Interface.Oxide.RootLogger.Write(LogType.Debug, "Made properties table {0}", propertiesTable);
                libraryTable["_properties"] = propertiesTable;
                libraryTable["_object"]     = library; // NOTE: Is this a security risk?
                LuaEnvironment["tmp"]       = null;

                // Bind all properties
                foreach (var name in library.GetPropertyNames())
                {
                    var property = library.GetProperty(name);
                    propertiesTable[name] = property;
                }

                // Bind the metatable
                //Interface.Oxide.RootLogger.Write(LogType.Debug, "setmetatable {0}", libraryMetaTable);
                (LuaEnvironment["setmetatable"] as LuaFunction).Call(libraryTable, libraryMetaTable);
            }
        }
Esempio n. 11
0
        public static void RegisterModule(LuaEnvironment env)
        {
            System.Diagnostics.Debug.Assert(env != null);
            var types = from ass in AppDomain.CurrentDomain.GetAssemblies()
                        from type in ass.GetTypes()
                        where type.Namespace == NAMESPACE
                            && type.IsValueType
                            && !type.IsAbstract
                            && type.IsPublic
                        select type;

            LuaTable module = LuaEnvironment.ValueConverter.CreateModuleFromTypes(types, ModuleName);

            module.SetNameValue("_G", env.Environment);
            module.SetNameValue("__index", module);
            env.SetNameValue(ModuleName, module);
        }
Esempio n. 12
0
        /// <summary>
        /// Initialises the Lua environment and compiles the Lua string for execution later on.
        /// </summary>
        protected virtual void InitExecuteLua()
        {
            if (initialised)
            {
                return;
            }

            // Cache a descriptive name to use in Lua error messages
            friendlyName = gameObject.name + "." + ParentBlock.BlockName + "." + "ExecuteLua #" + CommandIndex.ToString();

            var flowchart = GetFlowchart();

            // See if a Lua Environment has been assigned to this Flowchart
            if (luaEnvironment == null)
            {
                LuaEnv = flowchart.LuaEnv;
            }

            // No Lua Environment specified so just use any available or create one.
            if (LuaEnv == null)
            {
                LuaEnv = LuaEnvironment.GetLua();
            }

            string s = GetLuaString();

            luaFunction = LuaEnv.LoadLuaFunction(s, friendlyName);

            // Add a binding to the parent flowchart
            if (flowchart.LuaBindingName != "")
            {
                Table globals = LuaEnv.Interpreter.Globals;
                if (globals != null)
                {
                    globals[flowchart.LuaBindingName] = flowchart;
                }
            }

            // Always initialise when playing in the editor.
            // Allows the user to edit the Lua script while the game is playing.
            if (!(Application.isPlaying && Application.isEditor))
            {
                initialised = true;
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Called when all other extensions have been loaded
        /// </summary>
        public override void OnModLoad()
        {
            foreach (var extension in Manager.GetAllExtensions())
            {
                if (!extension.IsGameExtension)
                {
                    continue;
                }

                WhitelistAssemblies = extension.WhitelistAssemblies;
                WhitelistNamespaces = extension.WhitelistNamespaces;
                break;
            }

            // Bind Lua specific libraries
            LoadLibrary(new LuaGlobal(Manager.Logger), "_G");
            LuaEnvironment.NewTable("datafile");
            LoadLibrary(new LuaDatafile(LuaEnvironment), "datafile");
            if (LuaEnvironment["util"] == null)
            {
                LuaEnvironment.NewTable("util");
            }
            LoadLibrary(new LuaUtil(LuaEnvironment), "util");

            // Bind any libraries to Lua
            foreach (var name in Manager.GetLibraries())
            {
                var path = name.ToLowerInvariant();
                var lib  = Manager.GetLibrary(name);
                if (lib.IsGlobal)
                {
                    path = "_G";
                }
                else if (LuaEnvironment[path] == null)
                {
                    LuaEnvironment.NewTable(path);
                }
                LoadLibrary(lib, path);
            }

            // Bind attributes to Lua
            LoadPluginFunctionAttribute("Command");
        }
Esempio n. 14
0
        private void HandleCommandCallback(LuaFunction func, IPlayer caller, string cmd, string[] args)
        {
            LuaEnvironment.NewTable("tmp");
            var argsTable = LuaEnvironment["tmp"] as LuaTable;

            LuaEnvironment["tmp"] = null;
            for (var i = 0; i < args.Length; i++)
            {
                argsTable[i + 1] = args[i];
            }
            try
            {
                func.Call(Table, caller, cmd, argsTable);
            }
            catch (Exception)
            {
                // TODO: Error handling and stuff
                throw;
            }
        }
Esempio n. 15
0
        public static void Reconstruct(String path, String output = "stdout")
        {
            if (!File.Exists(path))
            {
                Error("File doesn't exists.");
                return;
            }

            var code        = File.ReadAllText(path);
            var environment = new LuaEnvironment( );

            environment.AddAnalyser("fixparents", new Analysis.FixParentsAnalyser( ));
            environment.AddAnalyser("gotocheck", new Analysis.GotoTargetCheckAnalyser( ));
            environment.AddFolder("ConstantFolder 1st pass", new Folder.ConstantASTFolder( ));
            environment.AddAnalyser("AssignmentAnalyser", new Analysis.AssignmentAnalyser( ));
            environment.AddFolder("AssignmentFolder", new Folder.AssignmentFolder( ));
            //environment.AddFolder ( "ConstantFolder 2nd pass", new Folder.ConstantASTFolder ( ) );

            var sw1 = Stopwatch.StartNew( );

            Env.EnvFile file = environment.ProcessFile(path, code);
            sw1.Stop( );
            foreach (Error err in file.Errors)
            {
                Console.WriteLine($"{err.Location} [{err.Type}] {err.Message}");
            }

            var sw2 = Stopwatch.StartNew( );

            using (var mem = new MemoryStream( ))
                using (Stream fileStream = output == "stdout" ? Console.OpenStandardOutput( ) : File.OpenWrite(output))
                    using (var writer = new StreamWriter(fileStream, Encoding.UTF8))
                    {
                        var reconstructor = new FormattedLuaReconstructor( );
                        reconstructor.Construct(file.AST, mem);
                        writer.Write(Encoding.UTF8.GetString(mem.ToArray( )));
                    }
            sw2.Stop( );
            Console.WriteLine($"Time elapsed on parsing + analysing + folding: {HumanTime ( sw1 )}");
            Console.WriteLine($"Time elapsed on serializing code: {HumanTime ( sw2 )}");
        }
Esempio n. 16
0
        /// <summary>
        /// Creates a table that encapsulates the specified type
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private LuaTable CreateTypeTable(Type type)
        {
            // Make the table
            LuaEnvironment.NewTable("tmp");
            var tmp = LuaEnvironment["tmp"] as LuaTable;

            // Set the type field
            tmp["_type"] = type;

            // Is it generic?
            if (type.IsGenericType)
            {
                // Setup metamethod
                setmetatable.Call(tmp, generictypetablemeta);
            }
            // Is it an enum?
            else if (type.IsEnum)
            {
                // Set all enum fields
                var fields = type.GetFields().Where(x => x.IsLiteral);
                foreach (var value in fields)
                {
                    tmp[value.Name] = value.GetValue(null);
                }
            }
            else
            {
                // Bind all public static methods
                var methods   = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
                var processed = new HashSet <string>();
                foreach (var method in methods)
                {
                    if (!processed.Contains(method.Name))
                    {
                        // We need to check if this method is overloaded
                        var overloads = methods.Where(m => m.Name == method.Name).ToArray();
                        if (overloads.Length == 1)
                        {
                            // It's not, simply bind it
                            LuaEnvironment.RegisterFunction($"tmp.{method.Name}", method);
                        }
                        else
                        {
                            // It is, "overloads" holds all our method overloads
                            tmp[method.Name] = CreateOverloadSelector(overloads);
                        }

                        // Processed
                        processed.Add(method.Name);
                    }
                }

                // Make the public static field table
                LuaEnvironment.NewTable("sftbl");
                var sftbl = LuaEnvironment["sftbl"] as LuaTable;
                LuaEnvironment["sftbl"] = null;
                tmp["_sftbl"]           = sftbl;
                var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
                foreach (var field in fields)
                {
                    sftbl[field.Name] = field;
                }

                // Bind all nested types
                foreach (var nested in type.GetNestedTypes())
                {
                    tmp[nested.Name] = CreateTypeTable(nested);
                }

                // Setup metamethod
                setmetatable.Call(tmp, typetablemeta);
            }

            // Return it
            LuaEnvironment["tmp"] = null;
            return(tmp);
        }
Esempio n. 17
0
 private void Start()
 {
     buttons = FindObjectOfType <ButtonHandler>();
     lua     = FindObjectOfType <LuaEnvironment>();
 }
Esempio n. 18
0
 private void Start()
 {
     lua = FindObjectOfType <LuaEnvironment>();
     buttonParent.SetActive(false);
 }
Esempio n. 19
0
        /// <summary>
        /// Binds the specified base method to the PLUGIN table
        /// </summary>
        /// <param name="methodname"></param>
        /// <param name="luaname"></param>
        private void BindBaseMethod(string methodname, string luaname)
        {
            var method = GetType().GetMethod(methodname, BindingFlags.Static | BindingFlags.NonPublic);

            LuaEnvironment.RegisterFunction($"PLUGIN.{luaname}", method);
        }
Esempio n. 20
0
        /// <summary>
        /// Loads this plugin
        /// </summary>
        public override void Load()
        {
            // Load the plugin into a table
            var source = File.ReadAllText(Filename);

            if (Regex.IsMatch(source, @"PLUGIN\.Version\s*=\s*[\'|""]", RegexOptions.IgnoreCase))
            {
                throw new Exception("Plugin version is a string, Oxide 1.18 plugins are not compatible with Oxide 2");
            }
            var pluginfunc = LuaEnvironment.LoadString(source, Path.GetFileName(Filename));

            if (pluginfunc == null)
            {
                throw new Exception("LoadString returned null for some reason");
            }
            LuaEnvironment.NewTable("PLUGIN");
            Table = (LuaTable)LuaEnvironment["PLUGIN"];
            ((LuaFunction)LuaEnvironment["setmetatable"]).Call(Table, luaExt.PluginMetatable);
            Table["Name"] = Name;
            pluginfunc.Call();

            // Read plugin attributes
            if (!(Table["Title"] is string))
            {
                throw new Exception("Plugin is missing title");
            }
            if (!(Table["Author"] is string))
            {
                throw new Exception("Plugin is missing author");
            }
            if (!(Table["Version"] is VersionNumber))
            {
                throw new Exception("Plugin is missing version");
            }
            Title   = (string)Table["Title"];
            Author  = (string)Table["Author"];
            Version = (VersionNumber)Table["Version"];
            if (Table["Description"] is string)
            {
                Description = (string)Table["Description"];
            }
            if (Table["ResourceId"] is double)
            {
                ResourceId = (int)(double)Table["ResourceId"];
            }
            if (Table["HasConfig"] is bool)
            {
                HasConfig = (bool)Table["HasConfig"];
            }

            // Set attributes
            Table["Object"] = this;
            Table["Plugin"] = this;

            // Get all functions and hook them
            functions = new Dictionary <string, LuaFunction>();
            foreach (var keyobj in Table.Keys)
            {
                var key = keyobj as string;
                if (key == null)
                {
                    continue;
                }
                var value = Table[key];
                var func  = value as LuaFunction;
                if (func != null)
                {
                    functions.Add(key, func);
                }
            }
            if (!HasConfig)
            {
                HasConfig = functions.ContainsKey("LoadDefaultConfig");
            }

            // Bind any base methods (we do it here because we don't want them to be hooked)
            BindBaseMethods();

            // Deal with any attributes
            var attribs = Table["_attribArr"] as LuaTable;

            if (attribs != null)
            {
                var i = 0;
                while (attribs[++i] != null)
                {
                    var attrib     = attribs[i] as LuaTable;
                    var attribName = attrib["_attribName"] as string;
                    var attribFunc = attrib["_func"] as LuaFunction;
                    if (attribFunc != null && !string.IsNullOrEmpty(attribName))
                    {
                        HandleAttribute(attribName, attribFunc, attrib);
                    }
                }
            }

            // Clean up
            LuaEnvironment["PLUGIN"] = null;
        }
Esempio n. 21
0
 public GLuaParser(GLuaLexer lexer, LuaEnvironment environment) : base(lexer)
 {
     this.Environment = environment;
     this.RootScope   = this.CreateScope(null);
     this.ScopeStack  = new Stack <Scope> ( );
 }
Esempio n. 22
0
        /// <summary>
        /// Binds the specified base method to the PLUGIN table
        /// </summary>
        /// <param name="methodname"></param>
        /// <param name="luaname"></param>
        private void BindBaseMethod(string methodname, string luaname)
        {
            MethodInfo method = GetType().GetMethod(methodname, BindingFlags.Static | BindingFlags.NonPublic);

            LuaEnvironment.RegisterFunction(string.Format("PLUGIN.{0}", luaname), method);
        }
Esempio n. 23
0
        /// <summary>
        /// Loads this plugin
        /// </summary>
        public void Load()
        {
            // Load the plugin into a table
            string      source     = File.ReadAllText(Filename);
            LuaFunction pluginfunc = LuaEnvironment.LoadString(source, Path.GetFileName(Filename));

            if (pluginfunc == null)
            {
                throw new Exception("LoadString returned null for some reason");
            }
            LuaEnvironment.NewTable("PLUGIN");
            Table         = LuaEnvironment["PLUGIN"] as LuaTable;
            Name          = Path.GetFileNameWithoutExtension(Filename);
            Table["Name"] = Name;
            pluginfunc.Call();

            // Read plugin attributes
            if (Table["Title"] == null || !(Table["Title"] is string))
            {
                throw new Exception("Plugin is missing title");
            }
            if (Table["Author"] == null || !(Table["Author"] is string))
            {
                throw new Exception("Plugin is missing author");
            }
            if (Table["Version"] == null || !(Table["Version"] is VersionNumber))
            {
                throw new Exception("Plugin is missing version");
            }
            Title   = (string)Table["Title"];
            Author  = (string)Table["Author"];
            Version = (VersionNumber)Table["Version"];
            if (Table["ResourceId"] is int)
            {
                ResourceId = (int)Table["ResourceId"];
            }
            if (Table["HasConfig"] is bool)
            {
                HasConfig = (bool)Table["HasConfig"];
            }

            // Set attributes
            Table["Object"] = this;
            Table["Plugin"] = this;

            // Get all functions and hook them
            functions = new Dictionary <string, LuaFunction>();
            foreach (var keyobj in Table.Keys)
            {
                string key = keyobj as string;
                if (key != null)
                {
                    object      value = Table[key];
                    LuaFunction func  = value as LuaFunction;
                    if (func != null)
                    {
                        functions.Add(key, func);
                    }
                }
            }

            // Bind any base methods (we do it here because we don't want them to be hooked)
            BindBaseMethods();

            // Clean up
            LuaEnvironment["PLUGIN"] = null;
        }