Ejemplo n.º 1
0
        internal static int LuaImport(IntPtr L)
        {
            LuaModule luaModule = Instance;

            string fileName = LuaDLL.lua_tostring(L, 1);
            var    obj      = luaModule.Import(fileName);


            LuaObject.pushValue(L, obj);
            LuaObject.pushValue(L, true);
            return(2);
        }
Ejemplo n.º 2
0
    private void push_list(SDataBuff data, NParam o, IntPtr L)
    {
        Sio.SListReader plist = data.listReader;
        LuaAPI.lua_newtable(L);
        int top_index = LuaAPI.lua_gettop(L);
        int luaindex  = 0;

        if (plist != null && o.Container == ParamContainer.pparam_container_list)
        {
            Sio.SDataBuff d = new Sio.SDataBuff();
            while (plist.Next(d))
            {
                push_data(d, L, o);
                LuaAPI.xlua_rawseti(L, top_index, ++luaindex);
            }
        }
    }
Ejemplo n.º 3
0
 private Sio.SData format_List(IntPtr L, int index, NParam o)
 {
     Sio.SListWriter pl = new Sio.SListWriter();
     Sio.SData       d  = new Sio.SData(pl);
     if (LuaAPI.lua_istable(L, index))
     {
         int indexsize = (int)LuaAPI.xlua_objlen(L, index);
         for (int list_index = 1; list_index <= indexsize; ++list_index)
         {
             LuaAPI.xlua_rawgeti(L, index, list_index);
             Sio.SData td = format_data(o, L, LuaAPI.lua_gettop(L), false);
             pl.add(td);
             LuaAPI.lua_pop(L, 1);
         }
     }
     return(d);
 }
Ejemplo n.º 4
0
        private int LuaUsing(IntPtr l)
        {
            try
            {
                LuaDLL.luaL_checktype(l, 1, LuaTypes.LUA_TSTRING);
                string str = LuaDLL.lua_tostring(l, 1);

                string[] ns = str.Split('.');

                LuaDLL.lua_pushglobaltable(l);

                for (int n = 0; n < ns.Length; n++)
                {
                    LuaDLL.lua_getfield(l, -1, ns[n]);
                    if (!LuaDLL.lua_istable(l, -1))
                    {
                        return(LuaObject.error(l, "expect {0} is type table", ns));
                    }
                    LuaDLL.lua_remove(l, -2);
                }

                LuaDLL.lua_pushnil(l);
                while (LuaDLL.lua_next(l, -2) != 0)
                {
                    string key = LuaDLL.lua_tostring(l, -2);
                    LuaDLL.lua_getglobal(l, key);
                    if (!LuaDLL.lua_isnil(l, -1))
                    {
                        LuaDLL.lua_pop(l, 1);
                        return(LuaObject.error(l, "{0} had existed, import can't overload it.", key));
                    }
                    LuaDLL.lua_pop(l, 1);
                    LuaDLL.lua_setglobal(l, key);
                }

                LuaDLL.lua_pop(l, 1);

                LuaObject.pushValue(l, true);
                return(1);
            }
            catch (Exception e)
            {
                return(LuaObject.error(l, e));
            }
        }
Ejemplo n.º 5
0
        public IEnumerator Init()
        {
#if SLUA
            InitSLua();
#else
            var L = _luaEnv.L;
            //在lua G中增加import函数
            LuaDLL.lua_pushstdcallcfunction(L, LuaImport);
            LuaDLL.xlua_setglobal(L, "import");

            //TODO lua中需要require的第三方库加到这里,如果不需要则删除已添加的这几行
            _luaEnv.AddBuildin("rapidjson", XLua.LuaDLL.Lua.LoadRapidJson);
            _luaEnv.AddBuildin("lpeg", XLua.LuaDLL.Lua.LoadLpeg);
            _luaEnv.AddBuildin("pb", XLua.LuaDLL.Lua.LoadLuaProfobuf);
            _luaEnv.AddBuildin("ffi", XLua.LuaDLL.Lua.LoadFFI);
            yield return(null);
#endif

            CallScript("Init");

            IsInited = true;
        }
Ejemplo n.º 6
0
        public IEnumerator Init()
        {
#if SLUA
            int frameCount = 0;
            while (!_luaSvr.inited)
            {
                if (frameCount % 30 == 0)
                {
                    Log.LogWarning("SLua Initing...");
                }
                yield return(null);

                frameCount++;
            }
            var L = _luaSvr.luaState.L;
            LuaDLL.lua_pushcfunction(L, LuaImport);
            LuaDLL.lua_setglobal(L, "import");
            LuaDLL.lua_pushcfunction(L, LuaUsing);
            LuaDLL.lua_setglobal(L, "using");       // same as SLua's import, using namespace
            LuaDLL.lua_pushcfunction(L, ImportCSharpType);
            LuaDLL.lua_setglobal(L, "import_type"); // same as SLua's SLua.GetClass(), import C# type
#else
            var L = _luaEnv.L;
            LuaDLL.lua_pushstdcallcfunction(L, LuaImport);
            LuaDLL.xlua_setglobal(L, "import");

            //TODO lua中需要require的第三方库加到这里
            _luaEnv.AddBuildin("rapidjson", XLua.LuaDLL.Lua.LoadRapidJson);
            _luaEnv.AddBuildin("lpeg", XLua.LuaDLL.Lua.LoadLpeg);
            _luaEnv.AddBuildin("pb", XLua.LuaDLL.Lua.LoadLuaProfobuf);
            _luaEnv.AddBuildin("ffi", XLua.LuaDLL.Lua.LoadFFI);
            yield return(null);
#endif

            CallScript("Init");

            IsInited = true;
        }
Ejemplo n.º 7
0
        public void InitSLua()
        {
#if SLUA
            int frameCount = 0;
            while (!_luaSvr.inited)
            {
                if (frameCount % 30 == 0)
                {
                    Log.LogWarning("SLua Initing...");
                }
                yield return(null);

                frameCount++;
            }
            var L = _luaSvr.luaState.L;
            LuaDLL.lua_pushcfunction(L, LuaImport);
            LuaDLL.lua_setglobal(L, "import");
            LuaDLL.lua_pushcfunction(L, LuaUsing);
            LuaDLL.lua_setglobal(L, "using");       // same as SLua's import, using namespace
            LuaDLL.lua_pushcfunction(L, ImportCSharpType);
            LuaDLL.lua_setglobal(L, "import_type"); // same as SLua's SLua.GetClass(), import C# type
#endif
        }
Ejemplo n.º 8
0
        public static void Main(string[] args)
        {
            // args = new[] {"/Users/cn/a3/c308/client/Unity/Tools/excel/lua/app/CollectImg2Excel.lua"};

            // // no use
            // AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs eventArgs)
            // {
            //     string assemblyFile = (eventArgs.Name.Contains(','))
            //         ? eventArgs.Name.Substring(0, eventArgs.Name.IndexOf(','))
            //         : eventArgs.Name;
            //
            //     assemblyFile += ".dll";
            //
            //     // // Forbid non handled dll's
            //     // if (!LOAD_ASSEMBLIES.Contains(assemblyFile))
            //     // {
            //     //     return null;
            //     // }
            //
            //     string absoluteFolder = new FileInfo((new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath).Directory.FullName;
            //     string targetPath = Path.Combine(absoluteFolder, assemblyFile);
            //
            //     try
            //     {
            //         Console.WriteLine($"try load:{targetPath}");
            //         return Assembly.LoadFile(targetPath);
            //     }
            //     catch (Exception)
            //     {
            //         return null;
            //     }
            //     Console.WriteLine($"load:{targetPath}");
            // };


            // // no use 2
            // var PrivateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath + (System.IO.Path.PathSeparator+AppDomain.CurrentDomain.BaseDirectory+"lib");
            // AppDomain.CurrentDomain.SetupInformation.PrivateBinPath = PrivateBinPath;
            // Console.WriteLine($"PathSeparator:{System.IO.Path.PathSeparator}\nPrivateBinPath:{PrivateBinPath}=>{AppDomain.CurrentDomain.SetupInformation.PrivateBinPath}\nBaseDirectory:{AppDomain.CurrentDomain.BaseDirectory} ");


            // for (int i = 0; i < args.Length; i++)
            // {
            //     Debug.WriteLine("args{0}: {1}", i, args[i]);
            // }

            // var w = AppDomain.CurrentDomain.GetAssemblies();
            // var asm = Assembly.LoadFrom("");
            // asm.GetExportedTypes();

            // Activator.CreateInstance(typeof(String));

            // var l = LuaCallCSharpTypes.L;

            // var size = NPOI.SS.Util.ImageUtils.GetImageDimension(null);
            // var wb = new XSSFWorkbook();
            // var sheet = wb.GetSheet("");
            // var picInd = wb.AddPicture(new FileStream("", FileMode.Open), 6);
            // var helper = wb.GetCreationHelper();
            // var drawing = sheet.CreateDrawingPatriarch();
            // var anchor = helper.CreateClientAnchor();
            // anchor.Col1 = 0;
            // anchor.Col2 = 0;
            // anchor.Row1 = 5;
            // var pict = drawing.CreatePicture(anchor, picInd);
            // pict.Resize();


            LuaEnv luaenv = LuaEnvSingleton.Instance;
            var    L      = luaenv.L;

            if (0 == LuaAPI.xlua_getglobal(L, "_VERSION"))
            {
                Console.WriteLine($"{LuaAPI.lua_tostring(L, -1)}");
            }

            ExecutableDir = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/");// Application.ExecutablePath.Replace(Path.GetFileName(Application.ExecutablePath), "");

            luaenv.DoString("package.cpath = package.cpath .. ';./lib?.dylib;./?.dylib';"
                            + string.Format("package.cpath = package.cpath .. ';{0}lib?.dylib;{0}lib/lib?.dylib;{0}lib/?.dylib;{0}../lib/lib?.dylib;{0}../lib/?.dylib'", ExecutableDir)
                            );

            var initlua = ExecutableDir + "init.lua";

            if (File.Exists(initlua))
            {
                luaenv.DoFile(initlua);
            }

            var mainlua = ExecutableDir + "lua/main.lua";

            if (args.Length > 0)
            {
                mainlua = args[0];
                var maindir = mainlua.Substring(0, mainlua.LastIndexOf("/"));
                luaenv.DoString(string.Format("package.path = package.path .. ';{0}/../?.lua;{0}/?.lua;{0}/lua/?.lua;'", maindir)
                                + @"package.path = package.path .. ';lua/?.lua' .. ';../lua/?.lua';"
                                + string.Format("package.path = package.path .. ';{0}/?.lua;;{0}/lua/?.lua;'", ExecutableDir));

                LuaTable env = luaenv.NewTable();
                env.Set("__index", luaenv.Global);
                env.Set("__newindex", luaenv.Global);

                LuaTable argv = luaenv.NewTable();
                for (int i = 0; i < args.Length; ++i)
                {
                    // Debug.WriteLine($"cs-argv[{i}] = {args[i]}");
                    argv.Set(i, args[i]);
                }
                env.Set("argv", argv);
                env.SetMetaTable(env);

                if (File.Exists(mainlua))
                {
                    luaenv.DoFile(mainlua, env);
                }
            }
            else
            {
                luaenv.DoString(@"package.path = package.path .. ';lua/?.lua' .. ';../lua/?.lua';"
                                + string.Format("package.path = package.path .. ';{0}/?.lua;;{0}/lua/?.lua;'", ExecutableDir));
                // Debug.WriteLine("run default entry lua/main.lua");
                Debug.WriteLine(" usage:\n\tosx/unix: mono xlua.exe path/to/entry.lua");
                Debug.WriteLine("\twindows: xlua.exe path/to/entry.lua");
                Debug.WriteLine("Or type lua code in Interaction Mode\nGood luck.");
                Console.Write("xlua");


                // // XLua.LuaDLL.Lua.lua_pushcclosure(L, (IntPtr)(pmain), 0);
                // XLua.LuaDLL.Lua.xlua_pushinteger(L, args.Length - 1);
                // luaenv.Translator.PushAny(L, args);
                // var ok = pmain(L);
                // Console.WriteLine($"lua return: {ok}");


                // LuaDoREPL(L);
                //
                // return;
                //*
                var fhistory = "xlua.history.lua";
                System.ReadLine.HistoryEnabled = false;
                var historyList = ReadLine.GetHistory();
                if (File.Exists(fhistory))
                {
                    historyList.AddRange(File.ReadAllLines(fhistory)
                                         .GroupBy(i => i)
                                         .Select(i => i.First()));
                    // ReadLine.AddHistory(historyList.ToArray());
                }

                var history    = File.AppendText(fhistory);
                int historyIdx = 0;
                var cmd        = "";
                while (cmd != "quit" && cmd != "exit")
                {
                    cmd = cmd.Trim().Replace("\0", "");
                    if (!historyList.Contains(cmd))
                    {
                        history.WriteLine(cmd);
                        history.Flush();
                    }
                    if (cmd.Length > 0)
                    {
                        historyList.Add(cmd);
                    }
                    if (cmd == "cls")
                    {
                        Console.Clear();
                        goto next;
                    }
                    if (cmd != ""
                        // && !cmd.Contains(" ")
                        && !cmd.Contains("=") &&
                        !cmd.Contains("print")
                        )
                    {
                        if (!cmd.Contains(",") &&
                            !cmd.Contains(" ")
                            )
                        {
                            cmd = "return  tostring(" + cmd + ")";
                        }
                        else
                        {
                            cmd = "return " + cmd;
                        }
                    }

                    try
                    {
                        if (cmd.Length > 0)
                        {
                            try
                            {
                                var ret = luaenv.DoString(cmd);
                                if (ret != null && ret.Length > 0)
                                {
                                    foreach (var o in ret)
                                    {
                                        // ObjectTranslatorPool.Instance.Find(L).PushAny(L, o);
                                        // var v = o is null ? XLua.LuaDLL.Lua.lua_tostring(L, -1) : o.ToString();
                                        var v = o is null ? "nil or native_ptr try tostring(obj) again" : o.ToString();
                                        Console.Write("{0}\t", v);
                                    }

                                    Console.Write("\n");
                                }
                            }
                            catch (LuaException e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }
                    }
                    catch (LuaException e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message + "\n#trace: \n" + e.StackTrace);
                    }

next:
                    cmd = ReadLine.Read("> ");
                }// while
                history.Close();
                Console.WriteLine("\nexit no error.");
                // */
            }
        }
Ejemplo n.º 9
0
    private void push_data(Sio.SDataBuff data, IntPtr L, NParam o)
    {
        switch (data.type)
        {
        case SType.stype_bool:
            LuaAPI.lua_pushboolean(L, data.boolValue);
            break;

        case SType.stype_uchar:
            LuaAPI.xlua_pushuint(L, data.ucharValue);
            break;

        case SType.stype_char:
            LuaAPI.xlua_pushinteger(L, data.charValue);
            break;

        case SType.stype_short:
            LuaAPI.xlua_pushinteger(L, data.shortValue);
            break;

        case SType.stype_ushort:
            LuaAPI.xlua_pushuint(L, data.ushortValue);
            break;

        case SType.stype_int:
            LuaAPI.xlua_pushinteger(L, data.intValue);
            break;

        case SType.stype_uint:
            LuaAPI.xlua_pushuint(L, data.uintValue);
            break;

        case SType.stype_float:
            LuaAPI.lua_pushnumber(L, data.floatValue);
            break;

        case SType.stype_double:
            LuaAPI.lua_pushnumber(L, data.doubleValue);
            break;

        case SType.stype_long:
            LuaAPI.lua_pushint64(L, data.longValue);
            break;

        case SType.stype_string:
            LuaAPI.lua_pushstring(L, data.stringValue);
            break;

        case SType.stype_list:
            push_list(data, o, L);
            break;

        case SType.stype_map:
            push_map(data, o, L);
            break;

        default:
            Logger.LogError("push_data error!!!!!!!!!!!!!!! type:" + data.type.ToString());
            break;
        }
    }
Ejemplo n.º 10
0
    private Sio.SData format_data(NParam o, RealStatePtr L, int index, bool checklist)
    {
        if (checklist == true && o.Container == ParamContainer.pparam_container_list)
        {
            return(format_List(L, index, o));
        }
        else
        {
            switch (o.DType)
            {
            case ParamType.ptype_bool:
            {
                bool ans = LuaAPI.lua_toboolean(L, index);
                if (LuaAPI.lua_isboolean(L, index))
                {
                    ans = LuaAPI.lua_toboolean(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_char:
            case ParamType.ptype_uchar:
            {
                byte ans = 0;
                if (LuaAPI.lua_isnumber(L, index))
                {
                    ans = (byte)LuaAPI.xlua_tointeger(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_ushort:
            {
                UInt16 ans = 0;
                if (LuaAPI.lua_isnumber(L, index))
                {
                    ans = (UInt16)LuaAPI.xlua_tointeger(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_short:
            {
                Int16 ans = 0;
                if (LuaAPI.lua_isnumber(L, index))
                {
                    ans = (Int16)LuaAPI.xlua_tointeger(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_int:
            {
                int ans = 0;
                if (LuaAPI.lua_isnumber(L, index))
                {
                    ans = (int)LuaAPI.xlua_tointeger(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_uint:
            {
                uint ans = 0;
                if (LuaAPI.lua_isnumber(L, index))
                {
                    ans = (uint)LuaAPI.xlua_tointeger(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_float:
            {
                float ans = 0.0f;
                if (LuaAPI.lua_isnumber(L, index))
                {
                    ans = (float)LuaAPI.xlua_tointeger(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_double:
            {
                double ans = 0.0;
                if (LuaAPI.lua_isnumber(L, index))
                {
                    ans = (double)LuaAPI.xlua_tointeger(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_long:
            {
                long ans = 0;
                if (LuaAPI.lua_isint64(L, index))
                {
                    ans = LuaAPI.lua_toint64(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_ulong:
            {
                ulong ans = 0;
                if (LuaAPI.lua_isint64(L, index))
                {
                    ans = LuaAPI.lua_touint64(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_string:
            {
                string ans = string.Empty;
                if (LuaAPI.lua_isstring(L, index))
                {
                    ans = LuaAPI.lua_tostring(L, index);
                }
                return(new Sio.SData(ans));
            }

            case ParamType.ptype_object:
            {
                return(format_map(L, index, o));
            }

            default:
                break;
            }
        }
        return(null);
    }
Ejemplo n.º 11
0
    public bool Process(Core.Net.Client c, Core.Net.Package p, int messageid, SNet.NFunction pf)
    {
        if (c.isConnected)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(pf.Nm.Name);
            sb.Append(".");
            sb.Append(pf.Name);

            Logger.Log(string.Format("<color=#00ab00ff>>>>receive<<<,msgid:{0}({1})</color>", messageid, sb.ToString()));

            if (null != this.OnReceive)
            {
                this.OnReceive(messageid, p.Header.GetExtData(), p.Header.GetSeqNum());
            }

            if (null != this.OnReceivePackage)
            {
                this.OnReceivePackage(messageid, p.Data);
            }

//		    LuaFunction func = XLuaManager.Instance.GetLuaEnv().Global.Get<LuaFunction>(c.DispatchFunc);
            if (null != this.DispatchFunc)
            {
                var luaEnv = XLuaManager.Instance.GetLuaEnv();
                var L      = luaEnv.L;

                var translator = luaEnv.translator;
                int oldTop     = LuaAPI.lua_gettop(L);

                int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
                LuaAPI.lua_getref(L, this.DispatchFunc.GetLuaReference());

                translator.PushAny(L, c.SocketID);
                translator.PushAny(L, messageid);
                translator.PushAny(L, p.Header.GetExtData());
                translator.PushAny(L, p.Header.GetSeqNum());
                translator.PushAny(L, sb.ToString());
                int valueCount = 5;


                IList <NParam> param_list = pf.ParamList;
                if (p.Data != null)
                {
                    MemoryStream ms = new MemoryStream(p.Data);
                    for (int i = 0; i < param_list.Count; i++)
                    {
                        push_to_lua(param_list[i], ms, L);
                        valueCount++;
                    }
                }

                int error = LuaAPI.lua_pcall(L, valueCount, -1, errFunc);
                if (error != 0)
                {
                    luaEnv.ThrowExceptionFromError(oldTop);
                }

                LuaAPI.lua_remove(L, errFunc);
            }
        }

        return(true);
    }