示例#1
0
        /// <summary>
        /// Creates a .NET object
        /// format: script.create(type, ...) where ... is constructor args
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static LuaValue Create(LuaValue[] args)
        {
            Type t = null;

            t = AssemblyCache.FindType(args[0].Value.ToString());

            if (t == null)
            {
                BaseLib.Print(new LuaValue[] { new LuaString("Cannot find type '" + args[0].Value.ToString() + "' in loaded assemblies!") });
            }

            List <object> _args = new List <object>();
            int           i     = 0;

            foreach (LuaValue v in args)
            {
                if (i != 0)
                {
                    _args.Add(v.Value);
                }

                i++;
            }

            // create object.
            return(ObjectToLua.ToLuaValue(Activator.CreateInstance(t, _args.ToArray())));
        }
示例#2
0
        public static LuaValue IterateDotNetList(LuaValue[] args)
        {
            LuaTable t = ObjectToLua.ToLuaTable(args[0].Value);

            // use some other function...
            return(Pairs(new LuaValue[] { t }));
        }
示例#3
0
        void Update()
        {
            while (server.Server.IsBound && server.Pending())
            {
                SocketStateObject newConn = new SocketStateObject();
                newConn.socket = server.AcceptSocket();
                connections.Add(newConn);
            }

            List <SocketStateObject> cleanup = new List <SocketStateObject>();

            byte[] sendData;
            lock (this)
            {
                sendData  = Encoding.UTF8.GetBytes(sendCache.ToString());
                sendCache = new StringBuilder();
            }

            LuaRuntime.GlobalEnvironment = luaEnv;
            foreach (SocketStateObject client in connections)
            {
                if (!client.socket.Connected)
                {
                    cleanup.Add(client);
                    continue;
                }

                if (client.socket.Available > 0)
                {
                    int br = client.socket.Receive(client.buffer, SocketStateObject.BufferSize, SocketFlags.Partial);
                    client.sb.Append(Encoding.UTF8.GetString(client.buffer, 0, br));
                    string tmp = client.sb.ToString();
                    if (tmp.Contains("\n"))
                    {
                        string[] pcs = tmp.Replace("\r", "").Split('\n');
                        foreach (string line in pcs.Take(pcs.Length - 1))
                        {
                            try
                            {
                                LuaRuntime.Run(line, luaEnv);
                            }
                            catch (Exception e)
                            {
                                A8Console.WriteLine(e.GetType().Name + ": " + e.Message);
                                luaEnv.SetNameValue("lastError", ObjectToLua.ToLuaValue(e));
                            }
                        }
                        client.sb = new StringBuilder(pcs.Last());
                    }
                }

                if (sendData.Length > 0)
                {
                    client.socket.Send(sendData);
                }
            }

            connections.RemoveAll(i => cleanup.Contains(i));
        }
示例#4
0
        public static LuaValue SLoad(LuaValue[] args)
        {
            string fn = (args[0] as LuaString).Text;
            // get the object
            object o = Serializer.Deserialize(fn);

            return(ObjectToLua.ToLuaValue(o));
        }
示例#5
0
        public void OnFlyByWire(FlightCtrlState state)
        {
            luaEnv.SetNameValue("state", ObjectToLua.ToLuaValue(state));

            MaybeRunCode(onFlyByWire);

            luaEnv.RemoveKey("state");
        }
示例#6
0
        public static LuaValue Call(LuaValue[] args)
        {
            string        method = args[0].ToString();
            List <object> args2  = new List <object>();

            for (int i = 1; i < args.Length; i++)
            {
                args2.Add(args[i].Value);
            }
            string n, m;

            n = method.Substring(0, method.LastIndexOf("."));
            m = method.Substring(method.LastIndexOf("."));
            AssemblyCache.ImportNamespace(n);
            Type t = AssemblyCache.FindType(n);

            if (t == null)
            {
                throw new Exception("Cannot find type '" + n + "'!");
            }
            BindingFlags bindingFlags = BindingFlags.IgnoreCase
                                        | BindingFlags.Public
                                        | BindingFlags.NonPublic
                                        | BindingFlags.Static
                                        | BindingFlags.FlattenHierarchy;

            // Start by looking for a method call
            MethodInfo m2 = t.GetMethod(m,
                                        bindingFlags | BindingFlags.InvokeMethod
                                        );

            if (m2 != null)
            {
                return(ObjectToLua.ToLuaValue(m2.Invoke(t, args2.ToArray())));
            }

            // Now loook for a property get
            PropertyInfo p = t.GetProperty(m, bindingFlags | BindingFlags.GetProperty);

            if (p != null)
            {
                return(ObjectToLua.ToLuaValue(p.GetGetMethod().Invoke(t, args2.ToArray())));
            }

            // Now look for a field get
            FieldInfo f = t.GetField(m, bindingFlags | BindingFlags.GetField);

            if (f != null)
            {
                return(ObjectToLua.ToLuaValue(f.GetValue(t)));
            }

            throw new Exception("Cannot find method '" + m + "' on class '" + n + "'!");
        }
 public void runScript(string script)
 {
     try
     {
         LuaRuntime.GlobalEnvironment = luaEnv;
         LuaRuntime.Run(script, luaEnv);
     }
     catch (Exception e)
     {
         A8Console.WriteLine(e.GetType().Name + ": " + e.Message);
         luaEnv.SetNameValue("lastError", ObjectToLua.ToLuaValue(e));
     }
 }
示例#8
0
        public static LuaValue ImportClass(LuaValue[] args)
        {
            string className = args[0].ToString();

            AssemblyCache.ImportNamespace(className);
            Type t = AssemblyCache.FindType(className);

            if (t == null)
            {
                throw new Exception("Cannot find type '" + className + "'!");
            }

            LuaValue mt = ObjectToLua.StaticClassToLuaTable(t);

            return(mt);
        }
 public void consoleRun()
 {
     A8Console.WriteLine("> " + line);
     if (history.LastOrDefault() != line)
     {
         history.Add(line);
     }
     historyPos = 0;
     try
     {
         LuaRuntime.GlobalEnvironment = luaEnv;
         LuaRuntime.Run(line, luaEnv);
     }
     catch (Exception e)
     {
         A8Console.WriteLine(e.GetType().Name + ": " + e.Message);
         luaEnv.SetNameValue("lastError", ObjectToLua.ToLuaValue(e));
     }
     line = "";
 }
        public MechJebModuleAutom8(MechJebCore core)
            : base(core)
        {
            instance = this;
            luaEnv   = LuaRuntime.CreateGlobalEnviroment();
            mechjeb  = new LuaTable();
            core.registerLuaMembers(mechjeb);
            luaEnv.SetNameValue("mechjeb", mechjeb);
            luaEnv.SetNameValue("vessel", ObjectToLua.ToLuaValue(vesselState));

            if (KSP.IO.File.Exists <MuMechJeb>("autorun.lua"))
            {
                try
                {
                    LuaRuntime.GlobalEnvironment = luaEnv;
                    LuaRuntime.RunFile("autorun.lua", luaEnv);
                }
                catch (Exception e)
                {
                    A8Console.WriteLine(e.GetType().Name + ": " + e.Message);
                    luaEnv.SetNameValue("lastError", ObjectToLua.ToLuaValue(e));
                }
            }
        }
 public override void onPartFixedUpdate()
 {
     luaEnv.SetNameValue("vessel", ObjectToLua.ToLuaValue(vesselState));
     base.onPartFixedUpdate();
 }
示例#12
0
        private LuaValue ExecuteAlternative(LuaTable enviroment, out bool isBreak)
        {
            LuaValue returnValue;

            LuaValue[] values     = this.ExprList.ConvertAll(expr => expr.Evaluate(enviroment)).ToArray();
            LuaValue[] neatValues = LuaMultiValue.UnWrapLuaValues(values);

            LuaValue state = neatValues[0];

            LuaTable table = new LuaTable(enviroment);

            this.Body.Enviroment = table;
            System.Collections.IDictionary dict = state.Value as System.Collections.IDictionary;
            System.Collections.IEnumerable ie   = state.Value as System.Collections.IEnumerable;
            if (dict != null)
            {
                foreach (object key in dict.Keys)
                {
                    //for (int i = 0; i < this.NameList.Count; i++)
                    //{
                    //table.SetNameValue(this.NameList[i], ObjectToLua.ToLuaValue(key));
                    //}
                    table.SetNameValue(this.NameList[0], ObjectToLua.ToLuaValue(key));
                    table.SetNameValue(this.NameList[1], ObjectToLua.ToLuaValue(dict[key]));

                    returnValue = this.Body.Execute(out isBreak);
                    if (returnValue != null || isBreak == true)
                    {
                        isBreak = false;
                        return(returnValue);
                    }
                }
            }
            else if (ie != null)
            {
                foreach (object obj in ie)
                {
                    for (int i = 0; i < this.NameList.Count; i++)
                    {
                        table.SetNameValue(this.NameList[i], ObjectToLua.ToLuaValue(obj));
                    }

                    returnValue = this.Body.Execute(out isBreak);
                    if (returnValue != null || isBreak == true)
                    {
                        isBreak = false;
                        return(returnValue);
                    }
                }
            }
            else
            {
                // its some other value...
                for (int i = 0; i < this.NameList.Count; i++)
                {
                    table.SetNameValue(this.NameList[i], ObjectToLua.ToLuaValue(state.Value));
                }

                returnValue = this.Body.Execute(out isBreak);
                if (returnValue != null || isBreak == true)
                {
                    isBreak = false;
                    return(returnValue);
                }

                isBreak = false;
                return(null);
            }
            isBreak = false;
            return(null);
        }
示例#13
0
        public static LuaValue Call(LuaValue[] args)
        {
            string        method = args[0].ToString();
            List <object> args2  = new List <object>();

            for (int i = 1; i < args.Length; i++)
            {
                args2.Add(args[i].Value);
            }
            string n, m;

            n = method.Substring(0, method.LastIndexOf("."));
            m = method.Substring(method.LastIndexOf(".") + 1);
            AssemblyCache.ImportNamespace(n);
            Type t = AssemblyCache.FindType(n);

            if (t == null)
            {
                throw new Exception("Cannot find type '" + n + "'!");
            }
            BindingFlags bindingFlags = BindingFlags.IgnoreCase
                                        | BindingFlags.Public
                                        | BindingFlags.NonPublic
                                        | BindingFlags.Static
                                        | BindingFlags.FlattenHierarchy;

            // Start by looking for a method call
            foreach (MethodInfo m2 in t.GetMethods(bindingFlags | BindingFlags.InvokeMethod))
            {
                if (m2.Name == m)
                {
                    UnityEngine.MonoBehaviour.print("Found " + m2 + " count = " + m2.GetGenericArguments().Length);
                    try
                    {
                        UnityEngine.MonoBehaviour.print("Trying " + m2);
                        object result = m2.Invoke(t, args2.ToArray());
                        return(ObjectToLua.ToLuaValue(result));
                    }
                    catch (ArgumentException e)
                    {
                        UnityEngine.MonoBehaviour.print(e);
                    }
                    catch (TargetParameterCountException e)
                    {
                        UnityEngine.MonoBehaviour.print(e);
                    }
                }
            }

            // Now loook for a property get
            PropertyInfo p = t.GetProperty(m, bindingFlags | BindingFlags.GetProperty);

            if (p != null)
            {
                return(ObjectToLua.ToLuaValue(p.GetGetMethod().Invoke(t, args2.ToArray())));
            }

            // Now look for a field get
            FieldInfo f = t.GetField(m, bindingFlags | BindingFlags.GetField);

            if (f != null)
            {
                return(ObjectToLua.ToLuaValue(f.GetValue(t)));
            }

            throw new Exception("Cannot find method '" + m + "' on class '" + n + "'!");
        }
示例#14
0
        public override LuaValue Evaluate(LuaValue baseValue, LuaTable enviroment)
        {
            LuaValue value = null;

            try { LuaValue.GetKeyValue(baseValue, new LuaString(this.Method)); } catch (Exception) { }
            LuaFunction function = value as LuaFunction;

            if (function != null)
            {
                if (this.Args.Table != null)
                {
                    return(function.Function.Invoke(new LuaValue[] { baseValue, this.Args.Table.Evaluate(enviroment) }));
                }
                else if (this.Args.String != null)
                {
                    return(function.Function.Invoke(new LuaValue[] { baseValue, this.Args.String.Evaluate(enviroment) }));
                }
                else
                {
                    List <LuaValue> args = this.Args.ArgList.ConvertAll(arg => arg.Evaluate(enviroment));
                    args.Insert(0, baseValue);
                    return(function.Function.Invoke(args.ToArray()));
                }
            } // method call on table would be like _G:script()
            else if ((baseValue as LuaTable) != null)
            {
                List <LuaValue> args = this.Args.ArgList.ConvertAll(arg => arg.Evaluate(enviroment));
                return(((baseValue as LuaTable).MetaTable.GetValue("__call") as LuaFunction).Invoke(args.ToArray()));
            }
            else if ((baseValue as LuaClass) != null)
            {
                LuaClass        c    = baseValue as LuaClass;
                List <LuaValue> args = this.Args.ArgList.ConvertAll(arg => arg.Evaluate(enviroment));
                args.Insert(0, new LuaString(this.Method));
                if (c.Self.MetaTable == null)
                {
                    c.GenerateMetaTable();
                }
                return((c.Self.MetaTable.GetValue("__call") as LuaFunction).Invoke(args.ToArray()));
            }
            else if ((baseValue as LuaUserdata) != null)
            {
                List <LuaValue> args = this.Args.ArgList.ConvertAll(arg => arg.Evaluate(enviroment));
                LuaUserdata     obj  = baseValue as LuaUserdata;
                object          o    = obj.Value;
                if (obj.MetaTable != null)
                {
                    if (obj.MetaTable.GetValue(this.Method) != null)
                    {
                        LuaValue o2 = obj.MetaTable.GetValue(this.Method);
                        if ((o2 as LuaFunction) != null)
                        {
                            return((o2 as LuaFunction).Invoke(args.ToArray()));
                        }
                        else if ((o2 as LuaTable) != null)
                        {
                            throw new NotImplementedException(); // TODO
                        }
                    }
                }
                return(ObjectToLua.ToLuaValue(o.GetType().GetMethod(this.Method, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Invoke(o, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, args.ToArray(), CultureInfo.CurrentCulture)));
            }
            else
            {
                throw new Exception("Invoke method call on non function value.");
            }
        }
示例#15
0
        public override LuaValue Evaluate(LuaValue baseValue, LuaTable enviroment)
        {
            LuaFunction function = baseValue as LuaFunction;

            if (function != null)
            {
                if (function.Function.Method.DeclaringType.FullName == "SharpLua.Library.BaseLib" &&
                    (function.Function.Method.Name == "loadstring" || function.Function.Method.Name == "dofile"))
                {
                    if (this.Args.String != null)
                    {
                        return(function.Function.Invoke(new LuaValue[] { this.Args.String.Evaluate(enviroment), enviroment }));
                    }
                    else
                    {
                        return(function.Function.Invoke(new LuaValue[] { this.Args.ArgList[0].Evaluate(enviroment), enviroment }));
                    }
                }

                if (this.Args.Table != null)
                {
                    return(function.Function.Invoke(new LuaValue[] { this.Args.Table.Evaluate(enviroment) }));
                }
                else if (this.Args.String != null)
                {
                    return(function.Function.Invoke(new LuaValue[] { this.Args.String.Evaluate(enviroment) }));
                }
                else
                {
                    List <LuaValue> args = this.Args.ArgList.ConvertAll(arg => arg.Evaluate(enviroment));
                    return(function.Function.Invoke(LuaMultiValue.UnWrapLuaValues(args.ToArray())));
                }
            }
            else if ((baseValue as LuaTable) != null)
            {
                List <LuaValue> args = this.Args.ArgList.ConvertAll(arg => arg.Evaluate(enviroment));
                args.Insert(0, baseValue);
                return(((baseValue as LuaTable).MetaTable.GetValue("__call") as LuaFunction).Invoke(args.ToArray()));
            }
            else if ((baseValue as LuaClass) != null)
            {
                LuaClass        c    = baseValue as LuaClass;
                List <LuaValue> args = this.Args.ArgList.ConvertAll(arg => arg.Evaluate(enviroment));
                //args.Insert(0, new LuaString(this.Method);
                if (c.Self.MetaTable == null)
                {
                    c.GenerateMetaTable();
                }
                return((c.Self.MetaTable.GetValue("__call") as LuaFunction).Invoke(args.ToArray()));
            }
            else if ((baseValue as LuaUserdata) != null)
            {
                List <LuaValue> args = this.Args.ArgList.ConvertAll(arg => arg.Evaluate(enviroment));
                LuaUserdata     u    = baseValue as LuaUserdata;
                if (u.MetaTable != null)
                {
                    if (u.MetaTable.GetValue("__call") != null)
                    {
                        return(ObjectToLua.ToLuaValue((u.MetaTable.GetValue("__call") as LuaFunction).Invoke(args.ToArray())));
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            else
            {
                throw new Exception("Invoke function call on non function value.");
            }
        }