示例#1
1
        /// <summary>
        /// Initializes the Lua environment
        /// </summary>
        private void InitializeLua()
        {
            // Create the Lua environment
            LuaEnvironment = new NLua.Lua();

            // Filter useless or potentially malicious libraries/functions
            LuaEnvironment["os"] = null;
            LuaEnvironment["io"] = null;
            LuaEnvironment["require"] = null;
            LuaEnvironment["dofile"] = null;
            LuaEnvironment["package"] = null;
            LuaEnvironment["luanet"] = null;
            LuaEnvironment["load"] = null;

            // Read util methods
            setmetatable = LuaEnvironment["setmetatable"] as LuaFunction;

            // Create metatables
            //Type mytype = GetType();
            LuaEnvironment.NewTable("tmp");
            overloadselectormeta = LuaEnvironment["tmp"] as LuaTable;
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("FindOverload", BindingFlags.Public | BindingFlags.Static));
            LuaEnvironment.NewTable("tmp");
            // Ideally I'd like for this to be implemented C# side, but using C#-bound methods as metamethods seems dodgy
            LuaEnvironment.LoadString(
            @"function tmp:__index( key )
            local sftbl = rawget( self, '_sftbl' )
            local field = sftbl[ key ]
            if (field) then return field:GetValue( nil ) end
            end
            function tmp:__newindex( key, value )
            local sftbl = rawget( self, '_sftbl' )
            local field = sftbl[ key ]
            if (field) then field:SetValue( nil, value ) end
            end
            ", "LuaExtension").Call();
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("ReadStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            //LuaEnvironment.RegisterFunction("tmp.__newindex", mytype.GetMethod("WriteStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            typetablemeta = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            LuaEnvironment.NewTable("tmp");
            LuaEnvironment.LoadString(
            @"function tmp:__index( key )
            if (type( key ) == 'table') then
            local baseType = rawget( self, '_type' )
            return util.SpecializeType( baseType, key )
            end
            end
            ", "LuaExtension").Call();
            generictypetablemeta = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            LuaEnvironment.NewTable("libraryMetaTable");
            LuaEnvironment.LoadString(
            @"function libraryMetaTable:__index( key )
            local ptbl = rawget( self, '_properties' )
            local property = ptbl[ key ]
            if (property) then return property:GetValue( rawget( self, '_object' ), null ) end
            end
            function libraryMetaTable:__newindex( key, value )
            local ptbl = rawget( self, '_properties' )
            local property = ptbl[ key ]
            if (property) then property:SetValue( rawget( self, '_object' ), value ) end
            end
            ", "LuaExtension").Call();
            libraryMetaTable = LuaEnvironment["libraryMetaTable"] as LuaTable;
            LuaEnvironment["libraryMetaTable"] = null;

            LuaEnvironment.NewTable("tmp");
            PluginMetatable = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment.LoadString(
            @"function tmp:__newindex( key, value )
            if (type( value ) ~= 'function') then return rawset( self, key, value ) end
            local activeAttrib = rawget( self, '_activeAttrib' )
            if (not activeAttrib) then return rawset( self, key, value ) end
            if (activeAttrib == self) then
            print( 'PluginMetatable.__newindex - self._activeAttrib was somehow self!' )
            rawset( self, key, value )
            return
            end
            local attribArr = rawget( self, '_attribArr' )
            if (not attribArr) then
            attribArr = {}
            rawset( self, '_attribArr', attribArr )
            end
            activeAttrib._func = value
            attribArr[#attribArr + 1] = activeAttrib
            rawset( self, '_activeAttrib', nil )
            end
            ", "LuaExtension").Call();
            LuaEnvironment["tmp"] = null;
        }
示例#2
0
        /// <summary>
        /// Initialises the Lua environment
        /// </summary>
        private void InitialiseLua()
        {
            // Create the Lua environment
            LuaEnvironment = new NLua.Lua();

            // Filter useless or potentially malicious libraries/functions
            LuaEnvironment["os"]      = null;
            LuaEnvironment["io"]      = null;
            LuaEnvironment["require"] = null;
            LuaEnvironment["dofile"]  = null;
            LuaEnvironment["package"] = null;
            LuaEnvironment["luanet"]  = null;
            LuaEnvironment["load"]    = null;

            // Read util methods
            setmetatable = LuaEnvironment["setmetatable"] as LuaFunction;

            // Create metatables
            //Type mytype = GetType();
            LuaEnvironment.NewTable("tmp");
            overloadselectormeta = LuaEnvironment["tmp"] as LuaTable;
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("FindOverload", BindingFlags.Public | BindingFlags.Static));
            LuaEnvironment.NewTable("tmp");
            // Ideally I'd like for this to be implemented C# side, but using C#-bound methods as metamethods seems dodgy
            LuaEnvironment.LoadString(
                @"function tmp:__index( key )
    local sftbl = rawget( self, '_sftbl' )
    local field = sftbl[ key ]
    if (field) then return field:GetValue( nil ) end
end
function tmp:__newindex( key, value )
    local sftbl = rawget( self, '_sftbl' )
    local field = sftbl[ key ]
    if (field) then field:SetValue( nil, value ) end
end
", "LuaExtension").Call();
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("ReadStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            //LuaEnvironment.RegisterFunction("tmp.__newindex", mytype.GetMethod("WriteStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            typetablemeta         = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            // Bind all namespaces and types
            foreach (var type in AppDomain.CurrentDomain.GetAssemblies()
                     .Where(AllowAssemblyAccess)
                     .SelectMany(Utility.GetAllTypesFromAssembly)
                     .Where(AllowTypeAccess))
            {
                // Get the namespace table
                LuaTable nspacetable = GetNamespaceTable(Utility.GetNamespace(type));

                // Bind the type
                nspacetable[type.Name] = CreateTypeTable(type);
            }
        }
示例#3
0
        /// <summary>
        /// Translates a single object from its C# form to its Lua form
        /// </summary>
        /// <param name="lua"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private static object TranslateConfigItemToLuaItem(NLua.Lua lua, object item)
        {
            // Switch on the object type
            if (item is int || item is float || item is double)
            {
                return(Convert.ToDouble(item));
            }
            else if (item is bool)
            {
                return(Convert.ToBoolean(item));
            }
            else if (item is string)
            {
                return(item);
            }
            else if (item is List <object> )
            {
                lua.NewTable("tmplist");
                var tbl = lua["tmplist"] as LuaTable;
                lua["tmplist"] = null;

                var list = item as List <object>;
                for (var i = 0; i < list.Count; i++)
                {
                    tbl[i + 1] = TranslateConfigItemToLuaItem(lua, list[i]);
                }

                return(tbl);
            }
            else
            {
                if (item is Dictionary <string, object> )
                {
                    lua.NewTable("tmpdict");
                    var tbl = lua["tmpdict"] as LuaTable;
                    lua["tmpdict"] = null;

                    var dict = item as Dictionary <string, object>;
                    foreach (var pair in dict)
                    {
                        CreateFullPath(pair.Key, tbl, lua);
                        tbl[pair.Key] = TranslateConfigItemToLuaItem(lua, pair.Value);
                    }

                    return(tbl);
                }
                return(null);
            }
        }
示例#4
0
        public static LuaTable MakeLuaTable(NLua.Lua luaInterpreter, string tableName)
        {
            luaInterpreter.NewTable(tableName);
            LuaTable taskTable = luaInterpreter.GetTable(tableName);

            return(taskTable);
        }
示例#5
0
        public static void Enumeration <T>(Lua lua)
        {
            #region Sanity checks
            if (lua == null)
            {
                throw new ArgumentNullException("lua");
            }
            #endregion

            Type type = typeof(T);
            if (!type.IsEnum)
            {
                throw new ArgumentException("The type must be an enumeration!");
            }

            string[] names  = Enum.GetNames(type);
            var      values = (T[])Enum.GetValues(type);

            lua.NewTable(type.Name);
            for (int i = 0; i < names.Length; i++)
            {
                string path = type.Name + "." + names[i];
                lua[path] = values[i];
            }
        }
示例#6
0
        public static void Enumeration <T>(Lua lua)
        {
            if (lua == null)
            {
                throw new ArgumentNullException(nameof(lua));
            }

            Type type = typeof(T);

            if (!type.IsEnum)
            {
                throw new ArgumentException("The type must be an enumeration!");
            }


            string[] names  = Enum.GetNames(type);
            var      values = (T[])Enum.GetValues(type);

            lua.NewTable(type.Name);

            for (int i = 0; i < names.Length; i++)
            {
                string path = type.Name + "." + names[i];
                lua.SetObjectToPath(path, values[i]);
            }
        }
示例#7
0
        public static void Enumeration <T> (Lua lua)
        {
            #region Sanity checks
            if (lua == null)
            {
                throw new ArgumentNullException("lua");
            }
            #endregion

            var type = typeof(T);

            if (!type.IsEnum())
            {
                throw new ArgumentException("The type must be an enumeration!");
            }

#if SILVERLIGHT
            string[] names  = type.GetFields().Where(x => x.IsLiteral).Select(field => field.Name).ToArray();
            var      values = type.GetFields().Where(x => x.IsLiteral).Select(field => (T)field.GetValue(null)).ToArray();
#else
            string[] names  = Enum.GetNames(type);
            var      values = (T[])Enum.GetValues(type);
#endif
            lua.NewTable(type.Name);

            for (int i = 0; i < names.Length; i++)
            {
                string path = type.Name + "." + names [i];
                lua [path] = values [i];
            }
        }
示例#8
0
        private static void PushVisibilityTable(NLua.Lua luaInterpreter)
        {
            luaInterpreter.NewTable("visibility");
            LuaTable luaTable = luaInterpreter.GetTable("visibility");

            luaTable["private"] = WorkshopItemVisibility.Private;
            luaTable["public"]  = WorkshopItemVisibility.Public;
        }
        private static void AddSetting(Lua lua, ModSetting setting)
        {
            var path = "settings.startup." + setting.Name;

            lua.NewTable(path);
            var table = lua.GetTable(path);

            table["value"] = setting.DefaultValue;
        }
示例#10
0
 public BubbleLua(Lua lua, bool init = true)
 {
     Lua = lua;
     if (!init)
         return;
     Lua.NewTable ("bubble");
     Bubble = (LuaTable)Lua ["bubble"];
     lua.DoString (EmbeddedResources.GetString ("BubbleEngine.LuaAPI.bubbleinternal.lua"));
 }
示例#11
0
        public static void Main(string[] args)
        {
            if(args.Length > 0)
            {
                // For attaching from the debugger
                // Thread.Sleep(20000);

                using(Lua lua = new Lua())
                {
                    //lua.OpenLibs();			// steffenj: Lua 5.1.1 API change (all libs already opened in Lua constructor!)
                    lua.NewTable("arg");
                    LuaTable argc = (LuaTable)lua["arg"];
                    argc[-1] = "LuaRunner";
                    argc[0] = args[0];

                    for(int i = 1; i < args.Length; i++)
                        argc[i] = args[i];

                    argc["n"] = args.Length - 1;

                    try
                    {
                        //Console.WriteLine("DoFile(" + args[0] + ");");
                        lua.DoFile(args[0]);
                    }
                    catch(Exception e)
                    {
                        // steffenj: BEGIN error message improved, output is now in decending order of importance (message, where, stacktrace)
                        // limit size of strack traceback message to roughly 1 console screen height
                        string trace = e.StackTrace;

                        if(e.StackTrace.Length > 1300)
                            trace = e.StackTrace.Substring(0, 1300) + " [...] (traceback cut short)";

                        Console.WriteLine();
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.Source + " raised a " + e.GetType().ToString());
                        Console.WriteLine(trace);

                        // wait for keypress if there is an error
                        Console.ReadKey();
                        // steffenj: END error message improved
                    }
                }
            }
            else
            {
                Console.WriteLine("LuaRunner -- runs Lua scripts with CLR access");
                Console.WriteLine("Usage: luarunner <script.lua> [{<arg>}]");
            }
        }
示例#12
0
        private static void CreateFullPath(string fullPath, LuaTable tbl, NLua.Lua lua)
        {
            var path = fullPath.Split('.');

            for (var i = 0; i < path.Length - 1; i++)
            {
                if (tbl[path[i]] == null)
                {
                    lua.NewTable("tmp");
                    var table = (LuaTable)lua["tmp"];
                    tbl[path[i]] = table;
                    lua["tmp"]   = null;
                    tbl          = table;
                }
            }
        }
示例#13
0
        public static void Main(string[] args)
        {
            try {
                using (Lua lua = new Lua()) {
                    //lua.OpenLibs();			// steffenj: Lua 5.1.1 API change (all libs already opened in Lua constructor!)
                    lua.NewTable("arg");
                    LuaTable argc = (LuaTable)lua ["arg"];

                    argc [0] = "NLua";

                    for (int i = 0; i < args.Length; i++)
                    {
                        argc [i + 1] = args [i];
                    }

                    argc ["n"] = args.Length;

                    lua.LoadCLRPackage();

                    try {
                        lua.DoString(lua_script, "lua");
                    } catch (Exception e) {
                        // limit size of stack traceback message to roughly 1 console screen height
                        string trace = e.StackTrace;

                        if (e.StackTrace.Length > 1300)
                        {
                            trace = e.StackTrace.Substring(0, 1300) + " [...] (traceback cut short)";
                        }

                        Console.WriteLine();
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.Source + " raised a " + e.GetType().ToString());
                        Console.WriteLine(trace);

                        // wait for key press if there is an error
                        Console.ReadKey();
                    }
                }
            } catch (Exception e) {
                Console.WriteLine();
                Console.WriteLine(e.Message);
                Console.WriteLine(e.Source + " raised a " + e.GetType().ToString());

                Console.ReadKey();
            }
        }
示例#14
0
        /// <summary>
        /// Copies and translates the contents of the specified config file into the specified table
        /// </summary>
        /// <param name="config"></param>
        /// <param name="lua"></param>
        /// <returns></returns>
        public static LuaTable TableFromConfig(DynamicConfigFile config, NLua.Lua lua)
        {
            // Make a table
            lua.NewTable("tmp");
            LuaTable tbl = lua["tmp"] as LuaTable;

            lua["tmp"] = null;

            // Loop each item in config
            foreach (var pair in config)
            {
                // Translate and set on table
                tbl[pair.Key] = TranslateConfigItemToLuaItem(lua, pair.Value);
            }

            // Return
            return(tbl);
        }
        private static Lua CreateLuaContext(IList <Mod> modList)
        {
            var lua = new Lua();

            lua.State.Encoding = Encoding.UTF8;
            lua.DoString(File.ReadAllText("pprint.lua"), "<ppriunt>");
            lua.DoString(File.ReadAllText("serpent.lua"), "<serpent>");

            lua.DoString(@"
defines = {}

defines.difficulty_settings = {}
defines.difficulty_settings.recipe_difficulty = {
    normal = 'normal',
}
defines.difficulty_settings.technology_difficulty = {
    normal = 'normal',
}

defines.direction = {
    north = 'north',
    east = 'east',
    south = 'south',
    west = 'west',
}

defines.entity_status = {}
defines.entity_status.working = nil
defines.entity_status.no_power = nil
defines.entity_status.no_fuel = nil
defines.entity_status.no_recipe = nil
defines.entity_status.no_input_fluid = nil
defines.entity_status.no_research_in_progress = nil
defines.entity_status.no_minable_resources = nil
defines.entity_status.low_input_fluid = nil
defines.entity_status.low_power = nil
defines.entity_status.disabled_by_control_behavior = nil
defines.entity_status.disabled_by_script = nil
defines.entity_status.fluid_ingredient_shortage = nil
defines.entity_status.fluid_production_overload = nil
defines.entity_status.item_ingredient_shortage = nil
defines.entity_status.item_production_overload = nil
defines.entity_status.marked_for_deconstruction = nil
defines.entity_status.missing_required_fluid = nil
defines.entity_status.missing_science_packs = nil
defines.entity_status.waiting_for_source_items = nil
defines.entity_status.waiting_for_space_in_destination = nil
defines.entity_status.waiting_to_launch_rocket = nil
", "<defines>");

            lua.DoString(@"
data = {}
data.raw = {}
function merge(t1, t2)
    if t1 == nil then return t2 end
    for k, v in pairs(t2) do
        if (type(v) == 'table') and (type(t1[k] or false) == 'table') then
            merge(t1[k], t2[k])
        else
            t1[k] = v
        end
    end
    return t1
end
-- LINE 15
function data:extend(t)
    -- print('############')
    -- pprint(t)
    for k, v in pairs(t) do
        -- print('-----------------')
        -- pprint(k)
        -- pprint(v)
        if type(v) == 'table' and v.type ~= nil then
            if self.raw[v.type] == nil then
                self.raw[v.type] = {}
            end
            self.raw[v.type][v.name] = merge(self.raw[v.type][v.name], v)
        end
    end
end
function table_size(t)
    local count = 0
    for k, v in pairs(t) do
        count = count + 1
    end
    return count
end
", "<startup>");
            lua.NewTable("mods");
            var modTable = lua.GetTable("mods");

            foreach (var mod in modList)
            {
                modTable[mod.InternalName] = mod.Version.ToString(3);
            }

            string TranslateName(string name)
            {
                var path = (string)lua.DoString(@"function script_path()
                    local str = debug.getinfo(3, 'S')
                    return str.source
                end

                return script_path()")[0];

                if (path.EndsWith(".lua"))
                {
                    var lastIndex = path.LastIndexOfAny(new[] { '/', '\\' });
                    path = path.Remove(lastIndex);
                }
                else
                {
                    path = null;
                }

                name = name.Replace('.', '/');
                if (!name.EndsWith(".lua"))
                {
                    name += ".lua";
                }

                if (currentMod.FileExists(name))
                {
                    return("__" + currentMod.InternalName + "__/" + name);
                }

                var modName = name.Split('/')[0];

                if (Regex.IsMatch(modName, "^__.+__$"))
                {
                    modName = modName[2..^ 2];
                    var mod = modList.FirstOrDefault(mod => mod.InternalName == modName);
                    if (mod != null)
                    {
                        return(name);
                    }
                }
示例#16
0
        private Main()
        {
            try
            {
                // Determine the absolute path of the server instance
                serverpath = Path.GetDirectoryName(Path.GetFullPath(Application.dataPath));
                string[] cmdline = Environment.GetCommandLineArgs();
                for (int i = 0; i < cmdline.Length - 1; i++)
                {
                    string arg = cmdline[i].ToLower();
                    if (arg == "-serverinstancedir" || arg == "-oxidedir")
                    {
                        try
                        {
                            serverpath = Path.GetFullPath(cmdline[++i]);
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("Failed to read server instance directory from command line!", ex);
                        }
                    }
                }

                // Ensure directories exist
                if (!Directory.Exists(serverpath)) Directory.CreateDirectory(serverpath);
                if (!Directory.Exists(GetPath("plugins"))) Directory.CreateDirectory(GetPath("plugins"));
                if (!Directory.Exists(GetPath("data"))) Directory.CreateDirectory(GetPath("data"));
                if (!Directory.Exists(GetPath("logs"))) Directory.CreateDirectory(GetPath("logs"));
                Logger.Message(string.Format("Loading at {0}...", serverpath));

                // Initialise the Unity component
                oxideobject = new GameObject("Oxide");
                oxidecomponent = oxideobject.AddComponent<OxideComponent>();
                oxidecomponent.Oxide = this;

                // Hook things that we can't hook using the IL injector
                var serverinit = UnityEngine.Object.FindObjectOfType(Type.GetType("ServerInit, Assembly-CSharp")) as MonoBehaviour;
                serverinit.gameObject.AddComponent<ServerInitHook>();

                // Initialise needed maps and collections
                datafiles = new Dictionary<string, Datafile>();
                plugins = new Dictionary<string, LuaTable>();
                timers = new HashSet<Timer>();
                webrequests = new HashSet<AsyncWebRequest>();

                // Initialise the lua state
                lua = new Lua();
                lua["os"] = null;
                lua["io"] = null;
                lua["require"] = null;
                lua["dofile"] = null;
                lua["package"] = null;
                lua["luanet"] = null;
                lua["load"] = null;

                // Register functions
                lua.NewTable("cs");
                RegisterFunction("cs.print", "lua_Print");
                RegisterFunction("cs.error", "lua_Error");
                RegisterFunction("cs.callplugins", "lua_CallPlugins");
                RegisterFunction("cs.findplugin", "lua_FindPlugin");
                RegisterFunction("cs.requeststatic", "lua_RequestStatic");
                RegisterFunction("cs.registerstaticmethod", "lua_RegisterStaticMethod");
                RegisterFunction("cs.requeststaticproperty", "lua_RequestStaticProperty");
                RegisterFunction("cs.requestproperty", "lua_RequestProperty");
                RegisterFunction("cs.requeststaticfield", "lua_RequestStaticField");
                RegisterFunction("cs.requestfield", "lua_RequestField");
                RegisterFunction("cs.requestenum", "lua_RequestEnum");
                RegisterFunction("cs.readproperty", "lua_ReadProperty");
                RegisterFunction("cs.readfield", "lua_ReadField");
                RegisterFunction("cs.castreadproperty", "lua_CastReadProperty");
                RegisterFunction("cs.castreadfield", "lua_CastReadField");
                RegisterFunction("cs.readulongpropertyasuint", "lua_ReadULongPropertyAsUInt");
                RegisterFunction("cs.readulongpropertyasstring", "lua_ReadULongPropertyAsString");
                RegisterFunction("cs.readulongfieldasuint", "lua_ReadULongFieldAsUInt");
                RegisterFunction("cs.readulongfieldasstring", "lua_ReadULongFieldAsString");
                RegisterFunction("cs.reloadplugin", "lua_ReloadPlugin");
                RegisterFunction("cs.getdatafile", "lua_GetDatafile");
                RegisterFunction("cs.dump", "lua_Dump");
                RegisterFunction("cs.createarrayfromtable", "lua_CreateArrayFromTable");
                RegisterFunction("cs.createtablefromarray", "lua_CreateTableFromArray");
                RegisterFunction("cs.gettype", "lua_GetType");
                RegisterFunction("cs.makegenerictype", "lua_MakeGenericType");
                RegisterFunction("cs.new", "lua_New");
                RegisterFunction("cs.newarray", "lua_NewArray");
                RegisterFunction("cs.convertandsetonarray", "lua_ConvertAndSetOnArray");
                RegisterFunction("cs.getelementtype", "lua_GetElementType");
                RegisterFunction("cs.newtimer", "lua_NewTimer");
                RegisterFunction("cs.sendwebrequest", "lua_SendWebRequest");
                RegisterFunction("cs.throwexception", "lua_ThrowException");
                RegisterFunction("cs.gettimestamp", "lua_GetTimestamp");
                RegisterFunction("cs.loadstring", "lua_LoadString");

                // Register constants
                lua.NewTable("bf");
                lua["bf.public_instance"] = BindingFlags.Public | BindingFlags.Instance;
                lua["bf.private_instance"] = BindingFlags.NonPublic | BindingFlags.Instance;
                lua["bf.public_static"] = BindingFlags.Public | BindingFlags.Static;
                lua["bf.private_static"] = BindingFlags.NonPublic | BindingFlags.Static;

                // Load the standard library
                Logger.Message("Loading standard library...");
                lua.LoadString(LuaOxideSTL.csfunc, "csfunc.stl").Call();
                lua.LoadString(LuaOxideSTL.json, "json.stl").Call();
                lua.LoadString(LuaOxideSTL.util, "util.stl").Call();
                lua.LoadString(LuaOxideSTL.type, "type.stl").Call();
                lua.LoadString(LuaOxideSTL.baseplugin, "baseplugin.stl").Call();
                lua.LoadString(LuaOxideSTL.rust, "rust.stl").Call();
                lua.LoadString(LuaOxideSTL.config, "config.stl").Call();
                lua.LoadString(LuaOxideSTL.plugins, "plugins.stl").Call();
                lua.LoadString(LuaOxideSTL.timer, "timer.stl").Call();
                lua.LoadString(LuaOxideSTL.webrequest, "webrequest.stl").Call();
                lua.LoadString(LuaOxideSTL.validate, "validate.stl").Call();

                // Read back required functions
                callunpacked = lua["callunpacked"] as LuaFunction;
                createplugin = lua["createplugin"] as LuaFunction;

                // Load all plugins
                Logger.Message("Loading plugins...");
                string[] files = Directory.GetFiles(GetPath("plugins"), "*.lua");
                foreach (string file in files)
                {
                    string pluginname = Path.GetFileNameWithoutExtension(file);
                    LuaTable plugininstance = createplugin.Call()[0] as LuaTable;
                    lua["PLUGIN"] = plugininstance;
                    plugininstance["Filename"] = file;
                    plugininstance["Name"] = pluginname;
                    try
                    {
                        currentplugin = pluginname;
                        string code = File.ReadAllText(GetPath(file));
                        lua.LoadString(code, file).Call();
                        plugins.Add(pluginname, plugininstance);
                        lua["PLUGIN"] = null;
                    }
                    catch (NLua.Exceptions.LuaScriptException luaex)
                    {
                        Logger.Error(string.Format("Failed to load plugin '{0}'!", file), luaex);
                    }
                }

                // Check plugin dependencies
                HashSet<string> toremove = new HashSet<string>();
                int numits = 0;
                while (numits == 0 || toremove.Count > 0)
                {
                    toremove.Clear();
                    foreach (var pair in plugins)
                    {
                        LuaTable dependencies = pair.Value["Depends"] as LuaTable;
                        if (dependencies != null)
                        {
                            foreach (var key in dependencies.Keys)
                            {
                                object value = dependencies[key];
                                if (value is string)
                                {
                                    if (!plugins.ContainsKey((string)value) || toremove.Contains((string)value))
                                    {
                                        Logger.Error(string.Format("The plugin '{0}' depends on missing or unloaded plugin '{1}' and won't be loaded!", pair.Key, value));
                                        toremove.Add(pair.Key);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    foreach (string name in toremove)
                        plugins.Remove(name);
                    numits++;
                }

                // Call Init and PostInit on all plugins
                CallPlugin("Init", null);
                CallPlugin("PostInit", null);
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("Error loading oxide!"), ex);
            }
        }
示例#17
0
文件: Main.cs 项目: khwoo1004/Oxide
        /// <summary>
        /// Loads Oxide
        /// </summary>
        private void Load()
        {
            // Initialise SSL
            System.Net.ServicePointManager.Expect100Continue = false;
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain,
                                       System.Net.Security.SslPolicyErrors sslPolicyErrors) => { return true; };
            System.Net.ServicePointManager.DefaultConnectionLimit = 200;

            // Determine the absolute path of the server instance
            serverpath = Path.GetDirectoryName(Path.GetFullPath(Application.dataPath));
            string[] cmdline = Environment.GetCommandLineArgs();
            for (int i = 0; i < cmdline.Length - 1; i++)
            {
                string arg = cmdline[i].ToLower();
                if (arg == "-serverinstancedir" || arg == "-oxidedir")
                {
                    try
                    {
                        serverpath = Path.GetFullPath(cmdline[++i]);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Failed to read server instance directory from command line!", ex);
                    }
                }
            }

            // Ensure directories exist
            if (!Directory.Exists(serverpath)) Directory.CreateDirectory(serverpath);
            if (!Directory.Exists(GetPath("plugins"))) Directory.CreateDirectory(GetPath("plugins"));
            if (!Directory.Exists(GetPath("data"))) Directory.CreateDirectory(GetPath("data"));
            if (!Directory.Exists(GetPath("logs"))) Directory.CreateDirectory(GetPath("logs"));
            Logger.Message(string.Format("Loading at {0}...", serverpath));

            // Initialise the Unity component
            oxideobject = new GameObject("Oxide");
            oxidecomponent = oxideobject.AddComponent<OxideComponent>();
            oxidecomponent.Oxide = this;

            // Hook things that we can't hook using the IL injector
            var serverinit = UnityEngine.Object.FindObjectOfType(Type.GetType("ServerInit, Assembly-CSharp")) as MonoBehaviour;
            serverinit.gameObject.AddComponent<ServerInitHook>();

            // Initialise needed maps and collections
            datafiles = new Dictionary<string, Datafile>();
            timers = new HashSet<Timer>();
            webrequests = new HashSet<AsyncWebRequest>();

            // Initialise the lua state
            lua = new Lua();
            lua["os"] = null;
            lua["io"] = null;
            lua["require"] = null;
            lua["dofile"] = null;
            lua["package"] = null;
            lua["luanet"] = null;
            lua["load"] = null;

            // Register functions
            lua.NewTable("cs");
            RegisterFunction("cs.print", "lua_Print");
            RegisterFunction("cs.error", "lua_Error");
            RegisterFunction("cs.callplugins", "lua_CallPlugins");
            RegisterFunction("cs.findplugin", "lua_FindPlugin");
            RegisterFunction("cs.requeststatic", "lua_RequestStatic");
            RegisterFunction("cs.registerstaticmethod", "lua_RegisterStaticMethod");
            RegisterFunction("cs.requeststaticproperty", "lua_RequestStaticProperty");
            RegisterFunction("cs.requestproperty", "lua_RequestProperty");
            RegisterFunction("cs.requeststaticfield", "lua_RequestStaticField");
            RegisterFunction("cs.requestfield", "lua_RequestField");
            RegisterFunction("cs.requestenum", "lua_RequestEnum");
            RegisterFunction("cs.readproperty", "lua_ReadProperty");
            RegisterFunction("cs.readfield", "lua_ReadField");
            RegisterFunction("cs.castreadproperty", "lua_CastReadProperty");
            RegisterFunction("cs.castreadfield", "lua_CastReadField");
            RegisterFunction("cs.readulongpropertyasuint", "lua_ReadULongPropertyAsUInt");
            RegisterFunction("cs.readulongpropertyasstring", "lua_ReadULongPropertyAsString");
            RegisterFunction("cs.readulongfieldasuint", "lua_ReadULongFieldAsUInt");
            RegisterFunction("cs.readulongfieldasstring", "lua_ReadULongFieldAsString");
            RegisterFunction("cs.readpropertyandsetonarray", "lua_ReadPropertyAndSetOnArray");
            RegisterFunction("cs.readfieldandsetonarray", "lua_ReadFieldAndSetOnArray");
            RegisterFunction("cs.reloadplugin", "lua_ReloadPlugin");
            RegisterFunction("cs.getdatafile", "lua_GetDatafile");
            RegisterFunction("cs.getdatafilelist", "lua_GetDatafileList"); // LMP
            RegisterFunction("cs.removedatafile", "lua_RemoveDatafile"); // LMP
            RegisterFunction("cs.dump", "lua_Dump");
            RegisterFunction("cs.createarrayfromtable", "lua_CreateArrayFromTable");
            RegisterFunction("cs.createtablefromarray", "lua_CreateTableFromArray");
            RegisterFunction("cs.gettype", "lua_GetType");
            RegisterFunction("cs.makegenerictype", "lua_MakeGenericType");
            RegisterFunction("cs.new", "lua_New");
            RegisterFunction("cs.newarray", "lua_NewArray");
            RegisterFunction("cs.convertandsetonarray", "lua_ConvertAndSetOnArray");
            RegisterFunction("cs.getelementtype", "lua_GetElementType");
            RegisterFunction("cs.newtimer", "lua_NewTimer");
            RegisterFunction("cs.sendwebrequest", "lua_SendWebRequest");
            RegisterFunction("cs.postwebrequest", "lua_PostWebRequest");
            RegisterFunction("cs.throwexception", "lua_ThrowException");
            RegisterFunction("cs.gettimestamp", "lua_GetTimestamp");
            RegisterFunction("cs.loadstring", "lua_LoadString");
            RegisterFunction("cs.createperfcounter", "lua_CreatePerfCounter");

            // Register constants
            lua.NewTable("bf");
            lua["bf.public_instance"] = BindingFlags.Public | BindingFlags.Instance;
            lua["bf.private_instance"] = BindingFlags.NonPublic | BindingFlags.Instance;
            lua["bf.public_static"] = BindingFlags.Public | BindingFlags.Static;
            lua["bf.private_static"] = BindingFlags.NonPublic | BindingFlags.Static;

            // Load the standard library
            Logger.Message("Loading standard library...");
            lua.LoadString(LuaOxideSTL.csfunc, "csfunc.stl").Call();
            lua.LoadString(LuaOxideSTL.json, "json.stl").Call();
            lua.LoadString(LuaOxideSTL.util, "util.stl").Call();
            lua.LoadString(LuaOxideSTL.type, "type.stl").Call();
            lua.LoadString(LuaOxideSTL.baseplugin, "baseplugin.stl").Call();
            lua.LoadString(LuaOxideSTL.rust, "rust.stl").Call();
            lua.LoadString(LuaOxideSTL.config, "config.stl").Call();
            lua.LoadString(LuaOxideSTL.plugins, "plugins.stl").Call();
            lua.LoadString(LuaOxideSTL.timer, "timer.stl").Call();
            lua.LoadString(LuaOxideSTL.webrequest, "webrequest.stl").Call();
            lua.LoadString(LuaOxideSTL.validate, "validate.stl").Call();

            // Initialise the plugin manager
            pluginmanager = new PluginManager();

            // Iterate all physical plugins
            Logger.Message("Loading plugins...");
            string[] files = Directory.GetFiles(GetPath("plugins"), "*.lua");
            foreach (string file in files)
            {
                // Load and register the plugin
                Plugin p = new Plugin(lua);
                if (p.Load(file)) pluginmanager.AddPlugin(p);
            }

            // Call Init and PostInit on all plugins
            pluginmanager.Call("Init", null);
            pluginmanager.Call("PostInit", null);
        }
示例#18
0
        public static void Main(string[] args)
        {
            try {

                using (Lua lua = new Lua ()) {
                    //lua.OpenLibs();			// steffenj: Lua 5.1.1 API change (all libs already opened in Lua constructor!)
                    lua.NewTable ("arg");
                    LuaTable argc = (LuaTable)lua ["arg"];

                    argc [0] = "NLua";

                    for (int i = 0; i < args.Length; i++) {
                        argc [i + 1] = args [i];
                    }

                    argc ["n"] = args.Length;

                    lua.LoadCLRPackage ();

                    try {
                        lua.DoString (lua_script,"lua");
                    } catch (Exception e) {
                        // limit size of stack traceback message to roughly 1 console screen height
                        string trace = e.StackTrace;

                        if (e.StackTrace.Length > 1300)
                            trace = e.StackTrace.Substring (0, 1300) + " [...] (traceback cut short)";

                        Console.WriteLine ();
                        Console.WriteLine (e.Message);
                        Console.WriteLine (e.Source + " raised a " + e.GetType ().ToString ());
                        Console.WriteLine (trace);

                        // wait for key press if there is an error
                        Console.ReadKey ();
                    }
                }
            } catch (Exception e) {
                Console.WriteLine ();
                Console.WriteLine (e.Message);
                Console.WriteLine (e.Source + " raised a " + e.GetType ().ToString ());

                Console.ReadKey ();
            }
        }
示例#19
0
        /// <summary>
        /// Initializes the Lua environment
        /// </summary>
        private void InitializeLua()
        {
            // Create the Lua environment
            LuaEnvironment = new NLua.Lua();

            // Filter useless or potentially malicious libraries/functions
            LuaEnvironment["os"]      = null;
            LuaEnvironment["io"]      = null;
            LuaEnvironment["require"] = null;
            LuaEnvironment["dofile"]  = null;
            LuaEnvironment["package"] = null;
            LuaEnvironment["luanet"]  = null;
            LuaEnvironment["load"]    = null;

            // Read util methods
            setmetatable = LuaEnvironment["setmetatable"] as LuaFunction;

            // Create metatables
            //Type mytype = GetType();
            LuaEnvironment.NewTable("tmp");
            overloadselectormeta = LuaEnvironment["tmp"] as LuaTable;
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("FindOverload", BindingFlags.Public | BindingFlags.Static));
            LuaEnvironment.NewTable("tmp");
            // Ideally I'd like for this to be implemented C# side, but using C#-bound methods as metamethods seems dodgy
            LuaEnvironment.LoadString(
                @"function tmp:__index( key )
    local sftbl = rawget( self, '_sftbl' )
    local field = sftbl[ key ]
    if (field) then return field:GetValue( nil ) end
end
function tmp:__newindex( key, value )
    local sftbl = rawget( self, '_sftbl' )
    local field = sftbl[ key ]
    if (field) then field:SetValue( nil, value ) end
end
", "LuaExtension").Call();
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("ReadStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            //LuaEnvironment.RegisterFunction("tmp.__newindex", mytype.GetMethod("WriteStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            typetablemeta         = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            LuaEnvironment.NewTable("tmp");
            LuaEnvironment.LoadString(
                @"function tmp:__index( key )
    if (type( key ) == 'table') then
        local baseType = rawget( self, '_type' )
        return util.SpecializeType( baseType, key )
    end
end
", "LuaExtension").Call();
            generictypetablemeta  = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            LuaEnvironment.NewTable("libraryMetaTable");
            LuaEnvironment.LoadString(
                @"function libraryMetaTable:__index( key )
    local ptbl = rawget( self, '_properties' )
    local property = ptbl[ key ]
    if (property) then return property:GetValue( rawget( self, '_object' ), null ) end
end
function libraryMetaTable:__newindex( key, value )
    local ptbl = rawget( self, '_properties' )
    local property = ptbl[ key ]
    if (property) then property:SetValue( rawget( self, '_object' ), value ) end
end
", "LuaExtension").Call();
            libraryMetaTable = LuaEnvironment["libraryMetaTable"] as LuaTable;
            LuaEnvironment["libraryMetaTable"] = null;

            LuaEnvironment.NewTable("tmp");
            PluginMetatable = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment.LoadString(
                @"function tmp:__newindex( key, value )
    if (type( value ) ~= 'function') then return rawset( self, key, value ) end
    local activeAttrib = rawget( self, '_activeAttrib' )
    if (not activeAttrib) then return rawset( self, key, value ) end
    if (activeAttrib == self) then
        print( 'PluginMetatable.__newindex - self._activeAttrib was somehow self!' )
        rawset( self, key, value )
        return
    end
    local attribArr = rawget( self, '_attribArr' )
    if (not attribArr) then
        attribArr = {}
        rawset( self, '_attribArr', attribArr )
    end
    activeAttrib._func = value
    attribArr[#attribArr + 1] = activeAttrib
    rawset( self, '_activeAttrib', nil )
end
", "LuaExtension").Call();
            LuaEnvironment["tmp"] = null;
        }
示例#20
0
 public LuaTable NewTable(string fullPath)
 {
     _lua.NewTable(fullPath);
     return(_lua.GetTable(fullPath));
 }