Exemple #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Script"/> class.
        /// </summary>
        /// <param name="coreModules">The core modules to be pre-registered in the default global table.</param>
        public Script(CoreModules coreModules)
        {
            Options          = new ScriptOptions(DefaultOptions);
            PerformanceStats = new PerformanceStatistics();
            Registry         = new Table(this);

            m_ByteCode      = new ByteCode(this);
            m_MainProcessor = new Processor(this, m_GlobalTable, m_ByteCode);
            m_GlobalTable   = new Table(this).RegisterCoreModules(coreModules);
            foreach (var t in TypeDescriptorRegistry.RegisteredTypes)
            {
                Type valType = t.Value.Type;
                if (valType.GetTypeInfo().Assembly.FullName != typeof(Script).GetTypeInfo().Assembly.FullName)
                {
                    // m_GlobalTable.RegisterModuleType(t.Value.Type);
                    if (t.Value is StandardUserDataDescriptor)
                    {
                        StandardUserDataDescriptor desc = (StandardUserDataDescriptor)t.Value;
                        foreach (var member in desc.Members)
                        {
                            if (member.Value is MethodMemberDescriptor)
                            {
                                MethodMemberDescriptor methDesc = (MethodMemberDescriptor)member.Value;
                                if (methDesc.IsConstructor)
                                {
                                    m_GlobalTable.Set(methDesc.Name, methDesc.GetCallbackAsDynValue(this));
                                }
                            }
                            else if (member.Value is OverloadedMethodMemberDescriptor)
                            {
                                OverloadedMethodMemberDescriptor methDesc = (OverloadedMethodMemberDescriptor)member.Value;
                                foreach (var overloadDesc in methDesc.m_Overloads)
                                {
                                    if (overloadDesc is MethodMemberDescriptor)
                                    {
                                        MethodMemberDescriptor actualDesc = (MethodMemberDescriptor)overloadDesc;
                                        if (actualDesc.IsConstructor)
                                        {
                                            //m_GlobalTable.Set(desc.FriendlyName, actualDesc.GetCallbackAsDynValue(this));
                                            m_GlobalTable.Set(desc.FriendlyName, DynValue.NewCallback(methDesc.GetCallbackFunction(this)));
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public static Table RegisterConstants(this Table table)
        {
            DynValue moonsharp_table = DynValue.NewTable(table.OwnerScript);
            Table    m = moonsharp_table.Table;

            table.Set("_G", DynValue.NewTable(table));
            table.Set("_VERSION", DynValue.NewString(string.Format("MoonSharp {0}", Script.VERSION)));
            table.Set("_MOONSHARP", moonsharp_table);

            m.Set("version", DynValue.NewString(Script.VERSION));
            m.Set("luacompat", DynValue.NewString(Script.LUA_VERSION));
            m.Set("platform", DynValue.NewString(Platform.Current.Name));

            return(table);
        }
        /// <summary>
        /// Registers the standard constants (_G, _VERSION, _MOONSHARP) to a table
        /// </summary>
        /// <param name="table">The table.</param>
        public static Table RegisterConstants(this Table table)
        {
            var moonsharpTable = DynValue.NewTable(table.OwnerScript);
            var m = moonsharpTable.Table;

            table.Set("_G", DynValue.NewTable(table));
            table.Set("_VERSION", DynValue.NewString($"MoonSharp {Script.VERSION}"));
            table.Set("_MOONSHARP", moonsharpTable);

            m.Set("version", DynValue.NewString(Script.VERSION));
            m.Set("luacompat", DynValue.NewString(Script.LUA_VERSION));
            m.Set("is_aot", DynValue.NewBoolean(Script.GlobalOptions.Platform.IsRunningOnAOT()));
            m.Set("is_mono", DynValue.NewBoolean(PlatformAutoDetector.IsRunningOnMono));

            return(table);
        }
 private static void RegisterScriptFieldAsConst(FieldInfo fi, object o, Table table, Type t, string name)
 {
     if (fi.FieldType == typeof(string))
     {
         string val = fi.GetValue(o) as string;
         table.Set(name, DynValue.NewString(val));
     }
     else if (fi.FieldType == typeof(double))
     {
         double val = (double)fi.GetValue(o);
         table.Set(name, DynValue.NewNumber(val));
     }
     else
     {
         throw new ArgumentException(string.Format("Field {0} does not have the right type - it must be string or double.", name));
     }
 }
        private static Table CreateModuleNamespace(Table gtable, Type t)
        {
            MoonSharpModuleAttribute attr = (MoonSharpModuleAttribute)t.GetCustomAttributes(typeof(MoonSharpModuleAttribute), false).First();

            if (string.IsNullOrEmpty(attr.Namespace))
            {
                return(gtable);
            }
            else
            {
                Table table = null;

                DynValue found = gtable.Get(attr.Namespace);

                if (found.Type == DataType.Table)
                {
                    table = found.Table;
                }
                else
                {
                    table = new Table(gtable.OwnerScript);
                    gtable.Set(attr.Namespace, DynValue.NewTable(table));
                }


                DynValue package = gtable.RawGet("package");

                if (package == null || package.Type != DataType.Table)
                {
                    gtable.Set("package", package = DynValue.NewTable(gtable.OwnerScript));
                }


                DynValue loaded = package.Table.RawGet("loaded");

                if (loaded == null || loaded.Type != DataType.Table)
                {
                    package.Table.Set("loaded", loaded = DynValue.NewTable(gtable.OwnerScript));
                }

                loaded.Table.Set(attr.Namespace, DynValue.NewTable(table));

                return(table);
            }
        }
Exemple #6
0
        /// <summary>
        /// Registers a module type to the specified table
        /// </summary>
        /// <param name="gtable">The table.</param>
        /// <param name="t">The type</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">If the module contains some incompatibility</exception>
        public static Table RegisterModuleType(this Table gtable, Type t)
        {
            Table table = CreateModuleNamespace(gtable, t);

            foreach (MethodInfo mi in Framework.Do.GetMethods(t).Where(__mi => __mi.IsStatic))
            {
                if (mi.GetCustomAttributes(typeof(MoonSharpModuleMethodAttribute), false).ToArray().Length > 0)
                {
                    MoonSharpModuleMethodAttribute attr = (MoonSharpModuleMethodAttribute)mi.GetCustomAttributes(typeof(MoonSharpModuleMethodAttribute), false).First();

                    if (!CallbackFunction.CheckCallbackSignature(mi, true))
                    {
                        throw new ArgumentException(string.Format("Method {0} does not have the right signature.", mi.Name));
                    }

#if NETFX_CORE
                    Delegate deleg = mi.CreateDelegate(typeof(Func <ScriptExecutionContext, CallbackArguments, DynValue>));
#else
                    Delegate deleg = Delegate.CreateDelegate(typeof(Func <ScriptExecutionContext, CallbackArguments, DynValue>), mi);
#endif

                    Func <ScriptExecutionContext, CallbackArguments, DynValue> func =
                        (Func <ScriptExecutionContext, CallbackArguments, DynValue>)deleg;


                    string name = (!string.IsNullOrEmpty(attr.Name)) ? attr.Name : mi.Name;

                    table.Set(name, DynValue.NewCallback(func, name));
                }
                else if (mi.Name == "MoonSharpInit")
                {
                    object[] args = new object[2] {
                        gtable, table
                    };
                    mi.Invoke(null, args);
                }
            }

            foreach (FieldInfo fi in Framework.Do.GetFields(t).Where(_mi => _mi.IsStatic && _mi.GetCustomAttributes(typeof(MoonSharpModuleMethodAttribute), false).ToArray().Length > 0))
            {
                MoonSharpModuleMethodAttribute attr = (MoonSharpModuleMethodAttribute)fi.GetCustomAttributes(typeof(MoonSharpModuleMethodAttribute), false).First();
                string name = (!string.IsNullOrEmpty(attr.Name)) ? attr.Name : fi.Name;

                RegisterScriptField(fi, null, table, t, name);
            }

            foreach (FieldInfo fi in Framework.Do.GetFields(t).Where(_mi => _mi.IsStatic && _mi.GetCustomAttributes(typeof(MoonSharpModuleConstantAttribute), false).ToArray().Length > 0))
            {
                MoonSharpModuleConstantAttribute attr = (MoonSharpModuleConstantAttribute)fi.GetCustomAttributes(typeof(MoonSharpModuleConstantAttribute), false).First();
                string name = (!string.IsNullOrEmpty(attr.Name)) ? attr.Name : fi.Name;

                RegisterScriptFieldAsConst(fi, null, table, t, name);
            }

            return(gtable);
        }
Exemple #7
0
        /// <summary>
        /// Registers the standard constants (_G, _VERSION, _MOONSHARP) to a table
        /// </summary>
        /// <param name="table">The table.</param>
        /// <returns></returns>
        public static Table RegisterConstants(this Table table)
        {
            DynValue moonsharp_table = DynValue.NewTable(table.OwnerScript);
            Table    m = moonsharp_table.Table;

            table.Set("_G", DynValue.NewTable(table));
            table.Set("_VERSION", DynValue.NewString(string.Format("MoonSharp {0}", Script.VERSION)));
            table.Set("_MOONSHARP", moonsharp_table);

            m.Set("version", DynValue.NewString(Script.VERSION));
            m.Set("luacompat", DynValue.NewString(Script.LUA_VERSION));
            m.Set("platform", DynValue.NewString(Script.GlobalOptions.Platform.GetPlatformName()));
            m.Set("is_aot", DynValue.NewBoolean(Script.GlobalOptions.Platform.IsRunningOnAOT()));
            m.Set("is_unity", DynValue.NewBoolean(PlatformAutoDetector.IsRunningOnUnity));
            m.Set("is_mono", DynValue.NewBoolean(PlatformAutoDetector.IsRunningOnMono));
            m.Set("is_clr4", DynValue.NewBoolean(PlatformAutoDetector.IsRunningOnClr4));
            m.Set("is_pcl", DynValue.NewBoolean(PlatformAutoDetector.IsPortableFramework));

            return(table);
        }
        private static void RegisterScriptField(FieldInfo fi, object o, Table table, Type t, string name)
        {
            if (fi.FieldType != typeof(string))
            {
                throw new ArgumentException(string.Format("Field {0} does not have the right type - it must be string.", name));
            }

            string val = fi.GetValue(o) as string;

            DynValue fn = table.OwnerScript.LoadFunction(val, table, name);

            table.Set(name, fn);
        }
        public static Table RegisterModuleType(this Table gtable, Type t)
        {
            Table table = CreateModuleNamespace(gtable, t);

            foreach (MethodInfo mi in t.GetMethods(BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic))
            {
                if (mi.GetCustomAttributes(typeof(MoonSharpMethodAttribute), false).Length > 0)
                {
                    MoonSharpMethodAttribute attr = (MoonSharpMethodAttribute)mi.GetCustomAttributes(typeof(MoonSharpMethodAttribute), false).First();

                    if (!ConversionHelper.CheckCallbackSignature(mi))
                    {
                        throw new ArgumentException(string.Format("Method {0} does not have the right signature.", mi.Name));
                    }

                    Func <ScriptExecutionContext, CallbackArguments, DynValue> func = (Func <ScriptExecutionContext, CallbackArguments, DynValue>)Delegate.CreateDelegate(typeof(Func <ScriptExecutionContext, CallbackArguments, DynValue>), mi);

                    string name = (!string.IsNullOrEmpty(attr.Name)) ? attr.Name : mi.Name;

                    table.Set(name, DynValue.NewCallback(func, name));
                }
                else if (mi.Name == "MoonSharpInit")
                {
                    object[] args = new object[2] {
                        gtable, table
                    };
                    mi.Invoke(null, args);
                }
            }

            foreach (FieldInfo fi in t.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic).Where(_mi => _mi.GetCustomAttributes(typeof(MoonSharpMethodAttribute), false).Length > 0))
            {
                MoonSharpMethodAttribute attr = (MoonSharpMethodAttribute)fi.GetCustomAttributes(typeof(MoonSharpMethodAttribute), false).First();
                string name = (!string.IsNullOrEmpty(attr.Name)) ? attr.Name : fi.Name;

                RegisterScriptField(fi, null, table, t, name);
            }
            foreach (FieldInfo fi in t.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic).Where(_mi => _mi.GetCustomAttributes(typeof(MoonSharpConstantAttribute), false).Length > 0))
            {
                MoonSharpConstantAttribute attr = (MoonSharpConstantAttribute)fi.GetCustomAttributes(typeof(MoonSharpConstantAttribute), false).First();
                string name = (!string.IsNullOrEmpty(attr.Name)) ? attr.Name : fi.Name;

                RegisterScriptFieldAsConst(fi, null, table, t, name);
            }

            return(gtable);
        }
            public static DynValue ClassToLuaTable(Script script, object obj)
            {
                MoonSharp.Interpreter.Table table = new MoonSharp.Interpreter.Table(script);
                var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);

                for (int i = 0; i < properties.Length; i++)
                {
                    var property = properties[i];

                    var value = property.GetValue(obj, null);
                    if (value == null)
                    {
                        continue;
                    }

                    if (value.GetType() == typeof(string))
                    {
                        table.Set(property.Name, DynValue.NewString((string)value));
                    }
                    else if (value.GetType() == typeof(int))
                    {
                        table.Set(property.Name, DynValue.NewNumber((int)value));
                    }
                    else if (value.GetType() == typeof(float))
                    {
                        table.Set(property.Name, DynValue.NewNumber((float)value));
                    }
                    else if (value.GetType() == typeof(bool))
                    {
                        table.Set(property.Name, DynValue.NewBoolean((bool)value));
                    }
                    else if (value is ProtoBuf.IExtensible)
                    {
                        table.Set(property.Name, ClassToLuaTable(script, value));
                    }
                    else if (value is IList)
                    {
                        IList list = value as IList;
                        MoonSharp.Interpreter.Table value_table = new MoonSharp.Interpreter.Table(script);
                        for (int j = 0; j < list.Count; ++j)
                        {
                            DynValue item = null;
                            if (list[j] is ProtoBuf.IExtensible)
                            {
                                item = ClassToLuaTable(script, list[j]);
                            }
                            else if (list[j] is int)
                            {
                                item = DynValue.NewNumber((int)list[j]);
                            }
                            else if (list[j] is float)
                            {
                                item = DynValue.NewNumber((float)list[j]);
                            }
                            else if (list[j] is string)
                            {
                                item = DynValue.NewString((string)list[j]);
                            }
                            else if (list[j] is bool)
                            {
                                item = DynValue.NewBoolean((bool)list[j]);
                            }
                            else
                            {
                                Debug.LogError("Convert List to lua table error: unsupported types " + list[j].GetType());
                            }
                            value_table.Append(item);
                        }
                        table.Set(property.Name, DynValue.NewTable(value_table));
                    }
                    else
                    {
                        Debug.LogError("Convert class to lua table error: unsupported types " + value);
                    }
                }

                return(DynValue.NewTable(table));
            }
Exemple #11
0
        public MoonSharp.Interpreter.Table GetCLRObjectTable(object obj, int level = 1, bool err = false)
        {
            level--;
            MoonSharp.Interpreter.Table ret = new MoonSharp.Interpreter.Table(MoonScript);
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
            {
                string name = descriptor.Name;
                if (TypeForm.OmittedProperties.Contains(name))
                {
                    continue;
                }
                object _value = null;

                try {
                    _value = descriptor.GetValue(obj);
                } catch (Exception e) {
                    ret.Set(name, MoonSharp.Interpreter.DynValue.NewString("[Error]"));
                    continue;
                }

                if (_value is int)
                {
                    ret.Set(name, MoonSharp.Interpreter.DynValue.NewNumber((int)_value));
                }
                else if (_value is double)
                {
                    ret.Set(name, MoonSharp.Interpreter.DynValue.NewNumber((double)_value));
                }
                else if (_value is byte)
                {
                    ret.Set(name, MoonSharp.Interpreter.DynValue.NewNumber((byte)_value));
                }
                else if (_value is string)
                {
                    ret.Set(name, MoonSharp.Interpreter.DynValue.NewString((string)_value));
                }
                else if (_value is bool)
                {
                    ret.Set(name, MoonSharp.Interpreter.DynValue.NewBoolean((bool)_value));
                }
                else if (_value != null && _value.GetType().IsEnum)
                {
                    ret.Set(name, MoonSharp.Interpreter.DynValue.NewNumber(Convert.ToInt32(_value)));
                }
                else if (level > 0)
                {
                    try {
                        ret.Set(name, MoonSharp.Interpreter.DynValue.NewTable(GetCLRObjectTable(_value, level, err)));
                    } catch (Exception e)
                    {
                        if (err)
                        {
                            ret.Set(name, MoonSharp.Interpreter.DynValue.NewString("[Cannot get inside]"));
                        }
                    }
                }
                else
                {
                    ret.Set(name, MoonSharp.Interpreter.DynValue.NewString(_value?.ToString()));
                }
            }

            return(ret);
        }