Ejemplo n.º 1
0
        static ILuaValue _processType(Type t, ILuaEnvironment env)
        {
            if (!typeof(ILuaValue).IsAssignableFrom(t))
            {
                return(null);
            }

            ConstructorInfo ci = t.GetConstructor(new Type[0]);

            if (ci == null)
            {
                ci = t.GetConstructor(new Type[] { typeof(ILuaEnvironment) });
                if (ci != null)
                {
                    ILuaValue mod = (ILuaValue)ci.Invoke(new[] { env });
                    return(mod.Invoke(LuaNil.Nil, false, -1, env.Runtime.CreateMultiValue()).Single());
                }
                return(null);
            }
            else
            {
                ILuaValue mod = (ILuaValue)ci.Invoke(null);
                return(mod.Invoke(LuaNil.Nil, false, -1, env.Runtime.CreateMultiValue()).Single());
            }
        }
Ejemplo n.º 2
0
                int[] _ops; // -4 = *L, -3 = *l, -2 = *a, -1 = *n

                public LinesHelper(ILuaEnvironment E, bool close, Stream stream, int[] ops)
                    : base(E, "io.lines")
                {
                    this._stream = new StreamReader(stream);
                    this._close = close;
                    this._ops = ops;
                }
Ejemplo n.º 3
0
 static ILuaMultiValue _getStream(ILuaValue file, ILuaEnvironment E, out Stream s)
 {
     s = null;
     if (file == LuaNil.Nil)
     {
         if (_output == null)
         {
             return(E.Runtime.CreateMultiValueFromObj(null, "No default output file set."));
         }
         s = _output;
     }
     else
     {
         if (file.ValueType == LuaValueType.Table)
         {
             s = ((ILuaTable)file).GetItemRaw(_stream).GetValue() as Stream;
             if (s == null)
             {
                 return(E.Runtime.CreateMultiValueFromObj(null, "Specified argument is not a valid file stream."));
             }
         }
         else if (file.ValueType == LuaValueType.UserData)
         {
             s = file.GetValue() as Stream;
         }
         else
         {
             return(E.Runtime.CreateMultiValueFromObj(null, "Specified argument is not a valid file stream."));
         }
     }
     return(null);
 }
Ejemplo n.º 4
0
            public static void Initialize(ILuaEnvironment E)
            {
                ILuaTable io = new LuaValues.LuaTable();

                io.SetItemRaw(new LuaString("close"), new close(E));
                io.SetItemRaw(new LuaString("flush"), new flush(E));
                io.SetItemRaw(new LuaString("input"), new input(E));
                io.SetItemRaw(new LuaString("lines"), new lines(E));
                io.SetItemRaw(new LuaString("open"), new open(E));
                io.SetItemRaw(new LuaString("output"), new output(E));
                io.SetItemRaw(new LuaString("read"), new read(E));
                io.SetItemRaw(new LuaString("tmpfile"), new tmpfile(E));
                io.SetItemRaw(new LuaString("type"), new type(E));
                io.SetItemRaw(new LuaString("write"), new write(E));

                _input  = E.Settings.Stdin;
                _output = E.Settings.Stdout;
                var _globals = E.GlobalsTable;

                _globals.SetItemRaw(new LuaString("io"), io);
                _globals.SetItemRaw(new LuaString("dofile"), new dofile(E));
                _globals.SetItemRaw(new LuaString("load"), new load(E));
                _globals.SetItemRaw(new LuaString("loadfile"), new loadfile(E));
                _globals.SetItemRaw(new LuaString("_STDIN"), _CreateFile(E.Settings.Stdin, E));
                _globals.SetItemRaw(new LuaString("_STDOUT"), _CreateFile(E.Settings.Stdout, E));
            }
Ejemplo n.º 5
0
        public override void AddBindings(ILuaEnvironment luaEnv)
        {
            if (!Init())
            {
                return;
            }

            MoonSharp.Interpreter.Script interpreter = luaEnv.Interpreter;
            Table globals = interpreter.Globals;

            if (globals == null)
            {
                Debug.LogError("Lua globals table is null");
                return;
            }

            // If the fungus global table is defined then add the store to it
            Table fungusTable = globals.Get("fungus").Table;

            if (fungusTable != null)
            {
                fungusTable["store"] = primeTable;
            }
            else
            {
                // Add the store as a global
                globals["store"] = primeTable;
            }
        }
            public static void Initialize(ILuaEnvironment E)
            {
                var table = E.GlobalsTable;
                Register(E, table, (Func<ILuaValue, ILuaValue, ILuaValue>)assert);
                Register(E, table, (Func<ILuaValue, string>)tostring);
                Register(E, table, (Func<string, int?, object[]>)collectgarbage);
                Register(E, table, (Action<string>)error);
                Register(E, table, (Func<ILuaValue, ILuaValue>)getmetatable);
                Register(E, table, (Func<ILuaTable, object[]>)ipairs);
                Register(E, table, (Func<ILuaTable, ILuaValue, object[]>)next);
                Register(E, table, (Func<ILuaTable, object[]>)pairs);
                Register(E, table, (Func<ILuaValue, ILuaValue, bool>)rawequal);
                Register(E, table, (Func<ILuaTable, ILuaValue, ILuaValue>)rawget);
                Register(E, table, (Func<ILuaTable, ILuaValue>)rawlen);
                Register(E, table, (Func<ILuaTable, ILuaValue, ILuaValue, ILuaValue>)rawset);
                Register(E, table, (Func<ILuaValue, object[], IEnumerable<object>>)select);
                Register(E, table, (Func<ILuaTable, ILuaTable, ILuaValue>)setmetatable);
                Register(E, table, (Func<ILuaTable, double?>)tonumber);
                Register(E, table, (Func<ILuaTable, string>)type);

                table.SetItemRaw(new LuaString("overload"), new overload(E));
                table.SetItemRaw(new LuaString("pcall"), new pcall(E));
                table.SetItemRaw(new LuaString("print"), new print(E));

                table.SetItemRaw(new LuaString("_VERSION"),
                                 E.Runtime.CreateValue(Standard._VERSION));
                table.SetItemRaw(new LuaString("_NET"),
                                 E.Runtime.CreateValue(Standard._NET));
                table.SetItemRaw(new LuaString("_G"), table);
            }
 /// <summary>
 /// Creates a new instance of LuaFrameworkMethod.
 /// </summary>
 /// <param name="E">The current environment.</param>
 /// <param name="name">The name of the method.</param>
 protected LuaFrameworkFunction(ILuaEnvironment E, string name)
     : base(name)
 {
     Contract.Requires(E != null);
     Contract.Requires(name != null);
     Environment = E;
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets a variables from a given Lua file using the given environment.
        /// </summary>
        /// <param name="env">The environment used to load the chunk.</param>
        /// <param name="path">The path to the Lua file.</param>
        /// <param name="names">The names of the variable to get.</param>
        /// <returns>The values of the variables or null if not found.  The array is
        /// never null.</returns>
        /// <exception cref="System.ArgumentException">If path is not in the
        /// correct format -or- if names contains a null string.</exception>
        /// <exception cref="System.ArgumentNullException">If any arguments are null.</exception>
        /// <exception cref="System.IO.FileNotFoundException">If the given file
        /// could not be found.</exception>
        /// <exception cref="System.InvalidCastException">If one of the variables
        /// could not be converted to the given type.</exception>
        /// <exception cref="ModMaker.Lua.Parser.SyntaxException">If there are
        /// syntax errors in the file.</exception>
        public static T[] GetVariables <T>(ILuaEnvironment env, string path, params string[] names)
        {
            if (names == null)
            {
                throw new ArgumentNullException(nameof(names));
            }

            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (env == null)
            {
                throw new ArgumentNullException(nameof(env));
            }

            if (names.Contains(null))
            {
                throw new ArgumentException(string.Format(Resources.CannotContainNull, nameof(names)));
            }

            path = Path.GetFullPath(path);
            if (!File.Exists(path))
            {
                throw new FileNotFoundException();
            }

            var parsed = PlainParser.Parse(
                env.Parser, File.ReadAllText(path), Path.GetFileNameWithoutExtension(path));
            var ret = env.CodeCompiler.Compile(env, parsed, Path.GetFileNameWithoutExtension(path));

            ret.Invoke(LuaNil.Nil, false, -1, LuaMultiValue.Empty);
            return(names.Select(s => env[s].As <T>()).ToArray());
        }
Ejemplo n.º 9
0
                readonly int[] _ops; // -4 = *L, -3 = *l, -2 = *a, -1 = *n

                public LinesHelper(ILuaEnvironment env, bool close, Stream stream, int[] ops)
                    : base(env, "io.lines")
                {
                    _stream = new StreamReader(stream);
                    _close  = close;
                    _ops    = ops;
                }
Ejemplo n.º 10
0
            public static void Initialize(ILuaEnvironment E)
            {
                var table = E.GlobalsTable;

                Register(E, table, (Func <ILuaValue, ILuaValue, ILuaValue>)assert);
                Register(E, table, (Func <ILuaValue, string>)tostring);
                Register(E, table, (Func <string, int?, object[]>)collectgarbage);
                Register(E, table, (Action <string>)error);
                Register(E, table, (Func <ILuaValue, ILuaValue>)getmetatable);
                Register(E, table, (Func <ILuaTable, object[]>)ipairs);
                Register(E, table, (Func <ILuaTable, ILuaValue, object[]>)next);
                Register(E, table, (Func <ILuaTable, object[]>)pairs);
                Register(E, table, (Func <ILuaValue, ILuaValue, bool>)rawequal);
                Register(E, table, (Func <ILuaTable, ILuaValue, ILuaValue>)rawget);
                Register(E, table, (Func <ILuaTable, ILuaValue>)rawlen);
                Register(E, table, (Func <ILuaTable, ILuaValue, ILuaValue, ILuaValue>)rawset);
                Register(E, table, (Func <ILuaValue, object[], IEnumerable <object> >)select);
                Register(E, table, (Func <ILuaTable, ILuaTable, ILuaValue>)setmetatable);
                Register(E, table, (Func <ILuaTable, double?>)tonumber);
                Register(E, table, (Func <ILuaTable, string>)type);

                table.SetItemRaw(new LuaString("overload"), new overload(E));
                table.SetItemRaw(new LuaString("pcall"), new pcall(E));
                table.SetItemRaw(new LuaString("print"), new print(E));

                table.SetItemRaw(new LuaString("_VERSION"),
                                 E.Runtime.CreateValue(Standard._VERSION));
                table.SetItemRaw(new LuaString("_NET"),
                                 E.Runtime.CreateValue(Standard._NET));
                table.SetItemRaw(new LuaString("_G"), table);
            }
Ejemplo n.º 11
0
        static void Register(ILuaEnvironment env, ILuaValue table, Delegate func, string name = null)
        {
            var funcValue = env.Runtime.CreateValue(func);
            var nameValue = env.Runtime.CreateValue(name ?? func.Method.Name);

            table.SetIndex(nameValue, funcValue);
        }
Ejemplo n.º 12
0
                int[] _ops; // -4 = *L, -3 = *l, -2 = *a, -1 = *n

                public LinesHelper(ILuaEnvironment E, bool close, Stream stream, int[] ops)
                    : base(E, "io.lines")
                {
                    this._stream = new StreamReader(stream);
                    this._close  = close;
                    this._ops    = ops;
                }
Ejemplo n.º 13
0
 /// <summary>
 /// Creates a new LuaThread object that calls the given method.
 /// </summary>
 /// <param name="E">The current environment.</param>
 /// <param name="method">The method to invoke.</param>
 internal LuaThreadNet(ILuaEnvironment E, ILuaValue method)
 {
     this.IsLua           = true;
     this.E_              = E;
     this.method_         = method;
     this.backing_        = new Thread(Do);
     this.releaseBacking_ = true;
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Creates a new LuaThread object that calls the given method and
 /// executes on the given thread.
 /// </summary>
 /// <param name="E">The current environment.</param>
 /// <param name="method">The method to invoke.</param>
 /// <param name="thread">The thread that will execute this thread.</param>
 internal LuaThreadNet(ILuaEnvironment E, Thread thread, ILuaValue method)
 {
     this.IsLua = true;
     this.E_ = E;
     this.method_ = method;
     this.backing_ = thread;
     this.releaseBacking_ = false;
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Creates a new LuaDefinedMethod from the given method.
        /// </summary>
        /// <param name="env">The current environment.</param>
        /// <param name="name">The name of the method, used for errors.</param>
        /// <param name="method">The method to invoke.</param>
        /// <param name="target">The target object.</param>
        /// <exception cref="System.ArgumentNullException">If method, E, or target is null.</exception>
        /// <exception cref="System.ArgumentException">If method does not have
        /// the correct method signature:
        /// ILuaMultiValue Method(ILuaEnvironment, ILuaMultiValue)</exception>
        public LuaDefinedFunction(ILuaEnvironment env, string name, MethodInfo method, object target)
            : base(name)
        {
            LuaFunc func = (LuaFunc)Delegate.CreateDelegate(typeof(LuaFunc), target, method);

            _method = func;
            _env    = env;
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Creates a new LuaThread object that calls the given method and executes on the given thread.
 /// </summary>
 /// <param name="env">The current environment.</param>
 /// <param name="method">The method to invoke.</param>
 /// <param name="thread">The thread that will execute this thread.</param>
 internal LuaThreadNet(ILuaEnvironment env, Thread thread, ILuaValue method)
 {
     IsLua           = true;
     _env            = env;
     _method         = method;
     _backing        = thread;
     _releaseBacking = false;
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Creates a new LuaThread object that calls the given method.
 /// </summary>
 /// <param name="E">The current environment.</param>
 /// <param name="method">The method to invoke.</param>
 internal LuaThreadNet(ILuaEnvironment E, ILuaValue method)
 {
     this.IsLua = true;
     this.E_ = E;
     this.method_ = method;
     this.backing_ = new Thread(Do);
     this.releaseBacking_ = true;
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Creates a new LuaThread object that calls the given method and
 /// executes on the given thread.
 /// </summary>
 /// <param name="E">The current environment.</param>
 /// <param name="method">The method to invoke.</param>
 /// <param name="thread">The thread that will execute this thread.</param>
 internal LuaThreadNet(ILuaEnvironment E, Thread thread, ILuaValue method)
 {
     this.IsLua           = true;
     this.E_              = E;
     this.method_         = method;
     this.backing_        = thread;
     this.releaseBacking_ = false;
 }
Ejemplo n.º 19
0
 /// <summary>
 /// Creates a new LuaThread object that calls the given method.
 /// </summary>
 /// <param name="env">The current environment.</param>
 /// <param name="method">The method to invoke.</param>
 internal LuaThreadNet(ILuaEnvironment env, ILuaValue method)
 {
     IsLua           = true;
     _env            = env;
     _method         = method;
     _backing        = new Thread(_do);
     _releaseBacking = true;
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates a new instance of LuaGlobalFunction using the given type.
        /// </summary>
        /// <param name="E">The current environment.</param>
        /// <param name="type">The type to use, must implement ILuaValue.</param>
        /// <returns>A new LuaGlobalFunction object.</returns>
        /// <exception cref="System.ArgumentNullException">If E or type is null.</exception>
        /// <exception cref="System.ArgumentException">If type does not implement
        /// ILuaValue.</exception>
        public static LuaGlobalFunction Create(ILuaEnvironment E, Type type)
        {
            Contract.Requires<ArgumentNullException>(E != null, "E");
            Contract.Requires<ArgumentNullException>(type != null, "type");
            Contract.Requires<ArgumentException>(typeof(ILuaValue).IsAssignableFrom(type), "The type must implement IMethod.");

            return new LuaGlobalFunction(E, type);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Creates a new WorkerThread object.
 /// </summary>
 /// <param name="owner">The factory that created this object.</param>
 /// <param name="env">The current environment.</param>
 public WorkerThread(ThreadPool owner, ILuaEnvironment env)
 {
     _status  = Status.Waiting;
     _owner   = owner;
     _env     = env;
     _backing = new Thread(_execute);
     _backing.IsBackground = true;
     _backing.Start();
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Creates a new WorkerThread object.
 /// </summary>
 /// <param name="owner">The factory that created this object.</param>
 /// <param name="E">The current environment.</param>
 public WorkerThread(ThreadPool owner, ILuaEnvironment E)
 {
     status_ = Status.Waiting;
     owner_ = owner;
     E_ = E;
     backing_ = new Thread(Execute);
     backing_.IsBackground = true;
     backing_.Start();
 }
Ejemplo n.º 23
0
 public Module(ILuaEnvironment E)
 {
     if (!(E is ILuaEnvironmentNet))
     {
         throw new InvalidOperationException(
                   "'require' only works with the NET version of the environment.");
     }
     E_ = E;
 }
Ejemplo n.º 24
0
 public Module(ILuaEnvironment E)
 {
     if (!(E is ILuaEnvironmentNet))
     {
         throw new InvalidOperationException(
             "'require' only works with the NET version of the environment.");
     }
     E_ = E;
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Creates a new WorkerThread object.
 /// </summary>
 /// <param name="owner">The factory that created this object.</param>
 /// <param name="E">The current environment.</param>
 public WorkerThread(ThreadPool owner, ILuaEnvironment E)
 {
     status_  = Status.Waiting;
     owner_   = owner;
     E_       = E;
     backing_ = new Thread(Execute);
     backing_.IsBackground = true;
     backing_.Start();
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Creates a new instance of LuaChunk with the given backing type.
 /// </summary>
 /// <param name="E">The current environment.</param>
 /// <param name="type">The generated type, must implement IMethod.</param>
 LuaGlobalFunction(ILuaEnvironment E, Type type)
     : base(type.Name)
 {
     Contract.Requires<ArgumentNullException>(E != null, "E");
     Contract.Requires<ArgumentNullException>(type != null, "type");
     Contract.Ensures(_Type != null);
     this._Type = type;
     this._E = E;
 }
Ejemplo n.º 27
0
            static ILuaMultiValue _read(int[] opts, StreamReader s, ILuaEnvironment E)
            {
                List <ILuaValue> ret = new List <ILuaValue>();

                foreach (var item in opts)
                {
                    switch (item)
                    {
                    case -4:
                        ret.Add(E.Runtime.CreateValue(s.EndOfStream ? null : s.ReadLine() + "\n"));
                        break;

                    case -3:
                        ret.Add(E.Runtime.CreateValue(s.EndOfStream ? null : s.ReadLine()));
                        break;

                    case -2:
                        ret.Add(E.Runtime.CreateValue(s.EndOfStream ? null : s.ReadToEnd()));
                        break;

                    case -1:
                        if (s.EndOfStream)
                        {
                            ret.Add(null);
                        }
                        else
                        {
                            double?d = NetHelpers.ReadNumber(s);
                            if (d.HasValue)
                            {
                                ret.Add(E.Runtime.CreateValue(d.Value));
                            }
                            else
                            {
                                ret.Add(LuaNil.Nil);
                            }
                        }
                        break;

                    default:
                        if (s.EndOfStream)
                        {
                            ret.Add(null);
                        }
                        else
                        {
                            char[] c = new char[item];
                            s.Read(c, 0, item);
                            ret.Add(E.Runtime.CreateValue(new string(c)));
                        }
                        break;
                    }
                }

                return(E.Runtime.CreateMultiValue(ret.ToArray()));
            }
Ejemplo n.º 28
0
 public SortComparer(ILuaEnvironment E, ILuaValue method)
 {
     if (method != null && method.ValueType != LuaValueType.Function)
     {
         throw new ArgumentException(
                   $"Invalid '{method.ValueType}' value for function 'table.sort'.");
     }
     _method = method;
     _env    = E;
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Creates a new instance of LuaRuntime.
        /// </summary>
        /// <returns>A new LuaRuntime object.</returns>
        /// <remarks>
        /// This is needed because the Invoke method needs to have 
        /// OpCodes.Tailcall in order to have proper tail calls support.
        /// Because C# does not add these, the Invoke method must be generated
        /// at runtime.
        /// </remarks>
        public static LuaRuntimeNet Create(ILuaEnvironment E)
        {
            if (runtimeType == null)
                CreateType();

            if (Lua.UseDynamicTypes)
                return (LuaRuntimeNet)Activator.CreateInstance(runtimeType, E);
            else
                return new LuaRuntimeNet(E);
        }
Ejemplo n.º 30
0
 public SortComparer(ILuaEnvironment E, ILuaValue method)
 {
     if (method != null && method.ValueType != LuaValueType.Function)
     {
         throw new ArgumentException(
                   "Invalid '" + method.ValueType + "' value for function 'table.sort'.");
     }
     method_ = method;
     E_      = E;
 }
Ejemplo n.º 31
0
        public static ILuaTable ToTable(this Entity <IUIPool> entity, ILuaEnvironment env)
        {
            var tbl = env.NewTable();

            tbl.Set("__index", entity);
            tbl.Set("id", entity.Get <Element>().Id.ToString());
            tbl.Set("name", entity.Get <Api.Name>().Value);
//            tbl.Set("parent", (Func<LuaTable>)(() => ToTable(_uiPool.GetElement(element.Get<Api.Parent>().Id))));
            return(tbl);
        }
Ejemplo n.º 32
0
        public virtual IEnumerable <ILuaMultiValue> GenericLoop(ILuaEnvironment env,
                                                                ILuaMultiValue args)
        {
            // TODO: Replace this.
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            if (env == null)
            {
                throw new ArgumentNullException(nameof(env));
            }

            ILuaValue target = args[0];
            object    temp   = target.GetValue();

            if (temp is IEnumerable <ILuaMultiValue> enumT)
            {
                foreach (var item in enumT)
                {
                    yield return(item);
                }
            }
            else if (temp is IEnumerable en)
            {
                foreach (var item in en)
                {
                    yield return(new LuaMultiValue(CreateValue(item)));
                }
            }
            else if (target.ValueType == LuaValueType.Function)
            {
                ILuaValue s   = args[1];
                ILuaValue var = args[2];

                while (true)
                {
                    var ret = target.Invoke(LuaNil.Nil, false, -1, CreateMultiValue(s, var));
                    if (ret == null || ret[0] == null || ret[0] == LuaNil.Nil)
                    {
                        yield break;
                    }

                    var = ret[0];

                    yield return(ret);
                }
            }
            else
            {
                throw new InvalidOperationException(
                          $"Cannot enumerate over an object of type '{args[0]}'.");
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Creates a new Lua object using the given lua environment.
        /// </summary>
        /// <param name="environment">
        /// The environment that Lua will execute in; if null, will use the default.
        /// </param>
        public Lua(ILuaEnvironment environment)
        {
            if (environment == null)
            {
                environment = new LuaEnvironmentNet(
                    new LuaSettings(Console.OpenStandardInput(), Console.OpenStandardOutput()));
            }

            _chunks = new List <ILuaValue>();
            _e      = environment;
        }
Ejemplo n.º 34
0
        public ILuaValue Load(ILuaEnvironment env, string name)
        {
            if (env == null)
            {
                throw new ArgumentNullException(nameof(env));
            }

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (_loaded.ContainsKey(name))
            {
                return(_loaded[name]);
            }

            List <Exception> exceptions = new List <Exception>();

            foreach (string s in this.Path.Split(';'))
            {
                string path = s.Replace("?", name);
                if (File.Exists(path))
                {
                    ILuaValue o = _processFile(path, name, name, env, exceptions);
                    if (o != null)
                    {
                        _loaded.Add(name, o);
                        return(o);
                    }
                }

                int i = name.IndexOf('.');
                while (i != -1)
                {
                    path = s.Replace("?", name.Substring(0, i));
                    if (File.Exists(path))
                    {
                        ILuaValue o = _processFile(path, name, name.Substring(i + 1), env, exceptions);
                        if (o != null)
                        {
                            _loaded.Add(name, o);
                            return(o);
                        }
                    }
                    i = name.IndexOf('.', i + 1);
                }
            }
            throw new AggregateException(
                      "Unable to load module '" + name + "' because a valid module could not be located.  " +
                      "See $Exception.InnerExceptions to see why.",
                      exceptions);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Creates a new LuaDefinedMethod from the given method.
        /// </summary>
        /// <param name="E">The current environment.</param>
        /// <param name="name">The name of the method, used for errors.</param>
        /// <param name="method">The method to invoke.</param>
        /// <param name="target">The target object.</param>
        /// <exception cref="System.ArgumentNullException">If method, E, or target is null.</exception>
        /// <exception cref="System.ArgumentException">If method does not have
        /// the correct method signature: 
        /// ILuaMultiValue Method(ILuaEnvironment, ILuaMultiValue)</exception>
        public LuaDefinedFunction(ILuaEnvironment E, string name, MethodInfo method, object target)
            : base(name)
        {
            Contract.Requires<ArgumentNullException>(E != null, "E");
            Contract.Requires<ArgumentNullException>(method != null, "method");
            Contract.Requires<ArgumentNullException>(target != null, "target");
            Contract.Ensures(_Method != null);

            LuaFunc func = (LuaFunc)Delegate.CreateDelegate(typeof(LuaFunc), target, method);
            Contract.Assume(func != null);

            this._Method = func;
            this._E = E;
        }
Ejemplo n.º 36
0
            static ILuaTable _CreateFile(Stream backing, ILuaEnvironment E)
            {
                ILuaTable ret = new LuaValues.LuaTable();

                ret.SetItemRaw(_stream, new LuaValues.LuaUserData <Stream>(backing));
                ret.SetItemRaw(new LuaString("close"), new close(E));
                ret.SetItemRaw(new LuaString("flush"), new flush(E));
                ret.SetItemRaw(new LuaString("lines"), new lines(E));
                ret.SetItemRaw(new LuaString("read"), new read(E));
                ret.SetItemRaw(new LuaString("seek"), new seek(E));
                ret.SetItemRaw(new LuaString("write"), new write(E));

                return(ret);
            }
Ejemplo n.º 37
0
        /// <summary>
        /// Compiles the current code into am IMethod.
        /// </summary>
        /// <param name="E">The current environment.</param>
        /// <returns>A new IMethod compiled from the current code.</returns>
        public ILuaValue CreateChunk(ILuaEnvironment E)
        {
            if (curNest == null)
            {
                throw new InvalidOperationException();
            }

            if (curNest.TypeDef != null)
            {
                curNest.TypeDef.CreateType();
            }
            Type t = curNest.Parrent.TypeDef.CreateType();

            return(LuaGlobalFunction.Create(E, t));
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Creates a new instance of LuaRuntime.
        /// </summary>
        /// <returns>A new LuaRuntime object.</returns>
        /// <remarks>
        /// This is needed because the Invoke method needs to have OpCodes.Tailcall in order to have
        /// proper tail calls support. Because C# does not add these, the Invoke method must be
        /// generated at runtime.
        /// </remarks>
        public static LuaRuntimeNet Create(ILuaEnvironment env)
        {
            if (_runtimeType == null)
            {
                _createType();
            }

            if (Lua.UseDynamicTypes)
            {
                return((LuaRuntimeNet)Activator.CreateInstance(_runtimeType, env));
            }
            else
            {
                return(new LuaRuntimeNet(env));
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Returns the first Lua Environment found in the scene, or creates one if none exists.
        /// This is a slow operation, call it once at startup and cache the returned value.
        /// </summary>
        public static ILuaEnvironment GetLua()
        {
            ILuaEnvironment luaEnv = GameObject.FindObjectOfType <LuaEnvironment>();

            if (luaEnv == null)
            {
                GameObject prefab = Resources.Load <GameObject>("Prefabs/LuaEnvironment");
                if (prefab != null)
                {
                    GameObject go = Instantiate(prefab) as GameObject;
                    go.name = "LuaEnvironment";
                    luaEnv  = go.GetComponent <ILuaEnvironment>();
                }
            }
            return(luaEnv);
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Creates a new instance of LuaClass.
        /// </summary>
        /// <param name="name">The simple name of the class.</param>
        /// <param name="_base">The base class of the class; or null.</param>
        /// <param name="interfaces">The interfaces that are inherited; or null.</param>
        /// <param name="E">The current environment.</param>
        internal LuaClass(string name, Type _base, Type[] interfaces, ILuaEnvironment E)
        {
            if (interfaces == null)
            {
                interfaces = new Type[0];
            }

            this.Name     = name;
            this.BaseType = _base;
            this._items   = new List <Item>();

            var inter = interfaces.SelectMany(t => t.GetInterfaces()).Union(interfaces).ToArray();

            this.Interfaces = new ReadOnlyCollection <Type>(inter);

            this._data = new ItemData(E, name, _base, inter);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Creates a new instance of LuaClass.
        /// </summary>
        /// <param name="name">The simple name of the class.</param>
        /// <param name="base">The base class of the class; or null.</param>
        /// <param name="interfaces">The interfaces that are inherited; or null.</param>
        /// <param name="env">The current environment.</param>
        internal LuaClass(string name, Type @base, Type[] interfaces, ILuaEnvironment env)
        {
            if (interfaces == null)
            {
                interfaces = new Type[0];
            }

            Name     = name;
            BaseType = @base;
            _items   = new List <Item>();

            var inter = interfaces.SelectMany(t => t.GetInterfaces()).Union(interfaces).ToArray();

            Interfaces = new ReadOnlyCollection <Type>(inter);

            _data = new ItemData(env, name, @base, inter);
        }
Ejemplo n.º 42
0
            public static void Initialize(ILuaEnvironment E)
            {
                ILuaValue bit32 = E.Runtime.CreateTable();
                Register(E, bit32, (Func<double, int, uint>)arshift);
                Register(E, bit32, (Func<double[], uint>)band);
                Register(E, bit32, (Func<double, uint>)bnot);
                Register(E, bit32, (Func<double[], uint>)bor);
                Register(E, bit32, (Func<double[], bool>)btest);
                Register(E, bit32, (Func<double[], uint>)bxor);
                Register(E, bit32, (Func<double, int, int, uint>)extract);
                Register(E, bit32, (Func<double, double, int, int, uint>)replace);
                Register(E, bit32, (Func<double, int, uint>)lrotate);
                Register(E, bit32, (Func<double, int, uint>)lshift);
                Register(E, bit32, (Func<double, int, uint>)rrotate);
                Register(E, bit32, (Func<double, int, uint>)rshift);

                E.GlobalsTable.SetItemRaw(E.Runtime.CreateValue("bit32"), bit32);
            }
Ejemplo n.º 43
0
        /// <summary>
        /// Searches and loads the module acording to the settings.
        /// </summary>
        /// <param name="name">The name of the module to find.</param>
        /// <param name="E">The environment to load to.</param>
        /// <returns>The loaded module, or null if it could not be loaded.</returns>
        /// <exception cref="System.ArgumentNullException">If E or name is null.</exception>
        public ILuaValue Load(ILuaEnvironment E, string name)
        {
            if (E == null)
                throw new ArgumentNullException("E");
            if (name == null)
                throw new ArgumentNullException("name");

            if (_loaded.ContainsKey(name))
                return _loaded[name];

            List<Exception> _e = new List<Exception>();
            foreach (string s in this.Path.Split(';'))
            {
                string path = s.Replace("?", name);
                if (File.Exists(path))
                {
                    ILuaValue o = ProcessFile(path, name, name, E, _e);
                    if (o != null)
                    {
                        _loaded.Add(name, o);
                        return o;
                    }
                }

                int i = name.IndexOf('.');
                while (i != -1)
                {
                    path = s.Replace("?", name.Substring(0, i));
                    if (File.Exists(path))
                    {
                        ILuaValue o = ProcessFile(path, name, name.Substring(i + 1), E, _e);
                        if (o != null)
                        {
                            _loaded.Add(name, o);
                            return o;
                        }
                    }
                    i = name.IndexOf('.', i + 1);
                }
            }
            throw new AggregateException("Unable to load module '" + name +
                "' because a valid module could not be located.  See $Exception.InnerExceptions to see why.", _e);
        }
Ejemplo n.º 44
0
            public static void Initialize(ILuaEnvironment E)
            {
                var str = E.Runtime.CreateTable();
                Register(E, str, (Func<string, int, int?, IEnumerable<int>>)byte_, "byte");
                Register(E, str, (Func<int[], string>)char_, "char");
                Register(E, str, (Func<string, string, int, bool, object[]>)find);
                Register(E, str, (Func<string, object[], string>)format);
                Register(E, str, (Func<string, string, object>)gmatch);
                Register(E, str, (Func<string, string, ILuaValue, int, string>)gsub);
                Register(E, str, (Func<string, int>)len);
                Register(E, str, (Func<string, string>)lower);
                Register(E, str, (Func<string, string, int, IEnumerable<string>>)match);
                Register(E, str, (Func<string, int, string, string>)rep);
                Register(E, str, (Func<string, string>)reverse);
                Register(E, str, (Func<string, int, int, string>)sub);
                Register(E, str, (Func<string, string>)upper);

                E.GlobalsTable.SetItemRaw(E.Runtime.CreateValue("string"), str);
            }
Ejemplo n.º 45
0
        public static void Initialize(ILuaEnvironment E)
        {
            LuaLibraries libraries = E.Settings.Libraries;

            if ((libraries & LuaLibraries.Standard) == LuaLibraries.Standard)
            {
                Standard.Initialize(E);
            }
            if ((libraries & LuaLibraries.IO) == LuaLibraries.IO)
            {
                IO.Initialize(E);
            }
            if ((libraries & LuaLibraries.String) == LuaLibraries.String)
            {
                String.Initialize(E);
            }
            if ((libraries & LuaLibraries.Math) == LuaLibraries.Math)
            {
                Math.Initialize(E);
                Bit32.Initialize(E);
            }
            if ((libraries & LuaLibraries.Table) == LuaLibraries.Table)
            {
                new Table(E).Initialize();
            }
            if ((libraries & LuaLibraries.OS) == LuaLibraries.OS)
            {
                new OS(E).Initialize();
            }
            if ((libraries & LuaLibraries.Modules) == LuaLibraries.Modules)
            {
                new Module(E).Initialize();
            }
            if ((libraries & LuaLibraries.Coroutine) == LuaLibraries.Coroutine)
            {
                new Coroutine(E).Initialize();
            }
        }
Ejemplo n.º 46
0
            public static void Initialize(ILuaEnvironment E)
            {
                ILuaValue math = E.Runtime.CreateTable();
                Register(E, math, (Func<double, double>)System.Math.Abs, "abs");
                Register(E, math, (Func<double, double>)System.Math.Asin, "asin");
                Register(E, math, (Func<double, double>)System.Math.Atan, "atan");
                Register(E, math, (Func<double, double, double>)System.Math.Atan2, "atan2");
                Register(E, math, (Func<double, double>)System.Math.Ceiling, "ceil");
                Register(E, math, (Func<double, double>)System.Math.Cos, "cos");
                Register(E, math, (Func<double, double>)System.Math.Cosh, "cosh");
                Register(E, math, (Func<double, double>)deg);
                Register(E, math, (Func<double, double>)System.Math.Exp, "exp");
                Register(E, math, (Func<double, double>)System.Math.Floor, "floor");
                Register(E, math, (Func<double, double, double>)System.Math.IEEERemainder, "fmod");
                Register(E, math, (Func<double, double[]>)frexp);
                math.SetIndex(E.Runtime.CreateValue("huge"),
                              E.Runtime.CreateValue(double.PositiveInfinity));
                Register(E, math, (Func<double, double, double>)ldexp);
                Register(E, math, (Func<double, double, double>)log);
                Register(E, math, (Func<double, double[], double>)max);
                Register(E, math, (Func<double, double[], double>)min);
                Register(E, math, (Func<double, double[]>)modf);
                math.SetIndex(E.Runtime.CreateValue("pi"),
                              E.Runtime.CreateValue(System.Math.PI));
                Register(E, math, (Func<double, double, double>)System.Math.Pow, "pow");
                Register(E, math, (Func<double, double>)rad);
                Register(E, math, (Func<int?, int?, double>)random);
                Register(E, math, (Action<int>)randomseed);
                Register(E, math, (Func<double, double>)System.Math.Sin, "sin");
                Register(E, math, (Func<double, double>)System.Math.Sinh, "sinh");
                Register(E, math, (Func<double, double>)System.Math.Sqrt, "sqrt");
                Register(E, math, (Func<double, double>)System.Math.Tan, "tan");
                Register(E, math, (Func<double, double>)System.Math.Tanh, "tanh");

                E.GlobalsTable.SetItemRaw(E.Runtime.CreateValue("math"), math);
            }
Ejemplo n.º 47
0
            public static void Initialize(ILuaEnvironment E)
            {
                ILuaTable io = new LuaValues.LuaTable();
                io.SetItemRaw(new LuaString("close"), new close(E));
                io.SetItemRaw(new LuaString("flush"), new flush(E));
                io.SetItemRaw(new LuaString("input"), new input(E));
                io.SetItemRaw(new LuaString("lines"), new lines(E));
                io.SetItemRaw(new LuaString("open"), new open(E));
                io.SetItemRaw(new LuaString("output"), new output(E));
                io.SetItemRaw(new LuaString("read"), new read(E));
                io.SetItemRaw(new LuaString("tmpfile"), new tmpfile(E));
                io.SetItemRaw(new LuaString("type"), new type(E));
                io.SetItemRaw(new LuaString("write"), new write(E));

                _input = E.Settings.Stdin;
                _output = E.Settings.Stdout;
                var _globals = E.GlobalsTable;
                _globals.SetItemRaw(new LuaString("io"), io);
                _globals.SetItemRaw(new LuaString("dofile"), new dofile(E));
                _globals.SetItemRaw(new LuaString("load"), new load(E));
                _globals.SetItemRaw(new LuaString("loadfile"), new loadfile(E));
                _globals.SetItemRaw(new LuaString("_STDIN"), _CreateFile(E.Settings.Stdin, E));
                _globals.SetItemRaw(new LuaString("_STDOUT"), _CreateFile(E.Settings.Stdout, E));
            }
Ejemplo n.º 48
0
        /// <summary>
        /// Compiles the current code into am IMethod.
        /// </summary>
        /// <param name="E">The current environment.</param>
        /// <returns>A new IMethod compiled from the current code.</returns>
        public ILuaValue CreateChunk(ILuaEnvironment E)
        {
            if (curNest == null)
                throw new InvalidOperationException();

            if (curNest.TypeDef != null)
                curNest.TypeDef.CreateType();
            Type t = curNest.Parrent.TypeDef.CreateType();
            return LuaGlobalFunction.Create(E, t);
        }
Ejemplo n.º 49
0
            static ILuaMultiValue _read(int[] opts, StreamReader s, ILuaEnvironment E)
            {
                List<ILuaValue> ret = new List<ILuaValue>();

                foreach (var item in opts)
                {
                    switch (item)
                    {
                        case -4:
                            ret.Add(E.Runtime.CreateValue(s.EndOfStream ? null : s.ReadLine() + "\n"));
                            break;
                        case -3:
                            ret.Add(E.Runtime.CreateValue(s.EndOfStream ? null : s.ReadLine()));
                            break;
                        case -2:
                            ret.Add(E.Runtime.CreateValue(s.EndOfStream ? null : s.ReadToEnd()));
                            break;
                        case -1:
                            if (s.EndOfStream)
                                ret.Add(null);
                            else
                            {
                                double? d = NetHelpers.ReadNumber(s);
                                if (d.HasValue)
                                    ret.Add(E.Runtime.CreateValue(d.Value));
                                else
                                    ret.Add(LuaNil.Nil);
                            }
                            break;
                        default:
                            if (s.EndOfStream)
                                ret.Add(null);
                            else
                            {
                                char[] c = new char[item];
                                s.Read(c, 0, item);
                                ret.Add(E.Runtime.CreateValue(new string(c)));
                            }
                            break;
                    }
                }

                return E.Runtime.CreateMultiValue(ret.ToArray());
            }
 public Coroutine(ILuaEnvironment E)
 {
     E_ = E;
 }
Ejemplo n.º 51
0
        static ILuaValue ProcessType(Type t, ILuaEnvironment E)
        {
            if (!typeof(ILuaValue).IsAssignableFrom(t))
                return null;

            ConstructorInfo ci = t.GetConstructor(new Type[0]);
            if (ci == null)
            {
                ci = t.GetConstructor(new Type[] { typeof(ILuaEnvironment) });
                if (ci != null)
                {
                    ILuaValue mod = (ILuaValue)ci.Invoke(new[] { E });
                    return mod.Invoke(LuaNil.Nil, false, -1, E.Runtime.CreateMultiValue()).Single();
                }
                return null;
            }
            else
            {
                ILuaValue mod = (ILuaValue)ci.Invoke(null);
                return mod.Invoke(LuaNil.Nil, false, -1, E.Runtime.CreateMultiValue()).Single();
            }
        }
Ejemplo n.º 52
0
 static ILuaMultiValue _getStream(ILuaValue file, ILuaEnvironment E, out Stream s)
 {
     s = null;
     if (file == LuaNil.Nil)
     {
         if (_output == null)
             return E.Runtime.CreateMultiValueFromObj(null, "No default output file set.");
         s = _output;
     }
     else
     {
         if (file.ValueType == LuaValueType.Table)
         {
             s = ((ILuaTable)file).GetItemRaw(_stream).GetValue() as Stream;
             if (s == null)
                 return E.Runtime.CreateMultiValueFromObj(null, "Specified argument is not a valid file stream.");
         }
         else if (file.ValueType == LuaValueType.UserData)
         {
             s = file.GetValue() as Stream;
         }
         else
             return E.Runtime.CreateMultiValueFromObj(null, "Specified argument is not a valid file stream.");
     }
     return null;
 }
Ejemplo n.º 53
0
 public dofile(ILuaEnvironment E) : base(E, "io.dofile") { }
Ejemplo n.º 54
0
 public load(ILuaEnvironment E) : base(E, "io.load") { }
Ejemplo n.º 55
0
 public loadfile(ILuaEnvironment E) : base(E, "io.loadfile") { }
Ejemplo n.º 56
0
 /// <summary>
 /// Creates a new instance of the default LuaRuntime.
 /// </summary>
 protected LuaRuntimeNet(ILuaEnvironment E) 
 {
     this.E = E;
     threadPool_ = new ThreadPool(E);
 }
Ejemplo n.º 57
0
        /// <summary>
        /// Starts a generic for loop and returns an enumerator object used to
        /// get the values.
        /// </summary>
        /// <param name="args">The input arguments.</param>
        /// <param name="E">The current environment.</param>
        /// <returns>An object used to enumerate over the loop, cannot be null.</returns>
        /// <exception cref="System.ArgumentNullException">If args or E is null.</exception>
        /// <exception cref="System.InvalidOperationException">If the object(s)
        /// cannot be enumerated over.</exception>
        public virtual IEnumerable<ILuaMultiValue> GenericLoop(ILuaEnvironment E, ILuaMultiValue args)
        {
            // TODO: Replace this.
            if (args == null)
                throw new ArgumentNullException("args");
            if (E == null)
                throw new ArgumentNullException("E");

            ILuaValue target = args[0];
            object temp = target.GetValue();
            if (temp is IEnumerable<ILuaMultiValue>)
            {
                foreach (var item in (IEnumerable<ILuaMultiValue>)temp)
                    yield return item;
            }
            else if (temp is IEnumerable)
            {
                foreach (var item in (IEnumerable)temp)
                {
                    yield return new LuaMultiValue(CreateValue(item));
                }
            }
            else if (target.ValueType == LuaValueType.Function)
            {
                ILuaValue s = args[1];
                ILuaValue var = args[2];

                while (true)
                {
                    var ret = target.Invoke(LuaNil.Nil, false, -1, CreateMultiValue(s, var));
                    if (ret == null || ret[0] == null || ret[0] == LuaNil.Nil)
                        yield break;
                    var = ret[0];

                    yield return ret;
                }
            }
            else
                throw new InvalidOperationException("Cannot enumerate over an object of type '" + args[0] + "'.");
        }
Ejemplo n.º 58
0
 public IEnumerable<ILuaMultiValue> GenericLoop(ILuaEnvironment E, ILuaMultiValue args)
 {
     Contract.Requires(E != null);
     Contract.Requires(args != null);
     Contract.Ensures(Contract.Result<IEnumerable<ILuaMultiValue>>() != null);
     return null;
 }
Ejemplo n.º 59
0
            static ILuaTable _CreateFile(Stream backing, ILuaEnvironment E)
            {
                ILuaTable ret = new LuaValues.LuaTable();
                ret.SetItemRaw(_stream, new LuaValues.LuaUserData<Stream>(backing));
                ret.SetItemRaw(new LuaString("close"), new close(E));
                ret.SetItemRaw(new LuaString("flush"), new flush(E));
                ret.SetItemRaw(new LuaString("lines"), new lines(E));
                ret.SetItemRaw(new LuaString("read"), new read(E));
                ret.SetItemRaw(new LuaString("seek"), new seek(E));
                ret.SetItemRaw(new LuaString("write"), new write(E));

                return ret;
            }
Ejemplo n.º 60
0
        ILuaValue ProcessFile(string path, string name, string partname, ILuaEnvironment E, List<Exception> _e)
        {
            if (path.EndsWith(".lua", StringComparison.OrdinalIgnoreCase))
            {
                if (!this.AllowLua)
                {
                    _e.Add(new InvalidOperationException("Cannot load file '" + path + "' because ModuleBinder.AllowLua is set to false."));
                    return null;
                }

                var item = PlainParser.Parse(E.Parser, System.IO.File.ReadAllText(path), System.IO.Path.GetFileNameWithoutExtension(path));
                var chunk = E.CodeCompiler.Compile(E, item, null);
                return chunk.Invoke(LuaNil.Nil, false, -1, LuaMultiValue.Empty).Single();
            }
            else if (path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
            {
                var aname = AssemblyName.GetAssemblyName(path);

                // validate against whitelist
                if (WhitelistPublicKeys != null)
                {
                    bool valid = false;
                    foreach (var key in WhitelistPublicKeys)
                    {
                        if (key == null)
                        {
                            if (aname.GetPublicKey() == null)
                                valid = true;
                        }
                        else
                        {
                            if (aname.GetPublicKey().ToStringBase16().ToLowerInvariant() == key.ToLowerInvariant())
                                valid = true;
                        }
                    }
                    if (!valid)
                    {
                        _e.Add(new InvalidOperationException("Cannot load file '" + path +
                            "' because the assembly's public key is not in the white-list."));
                        return null;
                    }
                }

                // Process the assembly
                if (AllowAssemblies)
                {
                    var a = Assembly.LoadFrom(path);
                    var types = a.GetTypes();
                    if (types == null || types.Length == 0)
                    {
                        _e.Add(new InvalidOperationException("Cannot load file '" + path + "' because it does not define any types."));
                        return null;
                    }
                    else if (types.Length > 1)
                    {
                        HashSet<Type> validTypes = new HashSet<Type>();

                        // check for the whole name
                        foreach (var item in types.Where(t => (t.Name == name || t.FullName == name) && ValidType(t)))
                            validTypes.Add(item);

                        // remove the first part of the name that is in the filename.
                        foreach (var item in types.Where(t => (t.Name == partname || t.FullName == partname) && ValidType(t)))
                            validTypes.Add(item);

                        if (validTypes.Count > 1)
                        {
                            _e.Add(new InvalidOperationException("Cannot load file '" + path + "' because more than one type matches the given name."));
                            return null;
                        }
                        else if (validTypes.Count == 0)
                        {
                            _e.Add(new InvalidOperationException("Cannot load file '" + path + "' because no types match the given name."));
                            return null;
                        }
                        else
                            return ProcessType(validTypes.First(), E);
                    }
                    else
                        return ProcessType(types[0], E);
                }
            }
            return null;
        }