Ejemplo n.º 1
0
    // Use this for initialization
    void Start()
    {
        int i = Random.Range(0, 10);

        Debug.Log(i);
        luaenv.DoString("CS.UnityEngine.Debug.Log('hello')");
        luaenv.DoString("print('lua hello world')");
        luaenv.DoString("require'main'");

        int a = luaenv.Global.Get <int>("a");

        Debug.Log(a);


        Table t = luaenv.Global.Get <Table>("t");

        Debug.Log(t.a);

        XLua.LuaFunction addfun = luaenv.Global.Get <XLua.LuaFunction>("addfun");
        object[]         c      = addfun.Call(1, 2);
        int cint = System.Convert.ToInt32(c[0]);

        Debug.Log(cint);

        XLua.LuaFunction update = luaenv.Global.Get <XLua.LuaFunction>("update");
        update.Call();
    }
Ejemplo n.º 2
0
    /// <summary>
    /// 执行main.lua
    /// </summary>
    public void Launch(string luaCleanupCode = null, string jsonString = null)
    {
        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();

        // 设置this到lua虚拟机中,脚本可以通过thisMod访问module hub对象
        luaenv.Global.Set("thisMod", this);

        // 模块的启动参数,主要是传递一些参数给lua脚本,参数是一个json字符串
        if (jsonString != null)
        {
            // lua脚本中通过launchArgs访问该json字符串
            luaenv.Global.Set("launchArgs", jsonString);
        }

        // 如果有lua代码需要首先执行,则先执行
        if (luaCleanupCode != null)
        {
            // 目前只有大厅模块启动子游戏模块时,该参数才不为null
            // 指向大厅模块lua脚本中提供的一段代码,这段代码的作用是
            // 重设一下游戏模块的lua虚拟机的_ENV和清理已经加载的脚本文件
            // 这是需要的,因为所有的游戏模块反复使用同一个lua虚拟机,
            // 例如如果不清理已经加载的lua文件,那么第二次进入同样的游戏模块
            // 它的代码将不会被重新执行,因为同样的文件已经require进来了
            luaenv.DoString(luaCleanupCode);
        }

        // 约定每一个模块都必须有一个main.lua文件,从这个文件开始执行
        var entryLuaFile = $"{modName}/main";

        luaenv.DoString($"require '{entryLuaFile}'", entryLuaFile);

        stopWatch.Stop();
        Debug.Log($"module {modName} launch total time:{stopWatch.Elapsed.TotalMilliseconds} milliseconds");
    }
Ejemplo n.º 3
0
    /// <summary>
    /// 初始化控制器
    /// </summary>
    private void init()
    {
        mStatus = EnumConfig.SystemControllerStatusEnum.INIT;
        mLuaenv = new XLua.LuaEnv();
        mLuaenv.DoString("CS.UnityEngine.Debug.Log('Lua Env create successful.')");

        mScriptEnv = mLuaenv.NewTable();

        Utils.BindMetaTable(mLuaenv, mScriptEnv);

        mScriptEnv.Set("self", this);

        foreach (var injection in injections)
        {
            mScriptEnv.Set(injection.name, injection.value);
        }
        mLuaenv.DoString(mLuaScript.text, "LuaTestScript", mScriptEnv);

        Action awake = mScriptEnv.Get <Action>("awake");

        if (awake != null)
        {
            awake();
        }

        mScriptEnv.Get("onStart", out mLuaStart);
        mScriptEnv.Get("update", out mLuaUpdate);
        mScriptEnv.Get("onDestroy", out mLuaOnDestroy);
    }
Ejemplo n.º 4
0
    // Start is called before the first frame update
    void Start()
    {
        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

        XLua.LuaEnv luaenv = new XLua.LuaEnv();
        var         main   = System.IO.File.ReadAllText(Application.dataPath + "\\main.lua");

        luaenv.DoString(main);
        stopwatch.Start();
        for (int i = 0; i < 1000; i++)
        {
            luaenv.DoString("StaticFunTest()");
        }
        Debug.LogWarning($"耗時 {stopwatch.Elapsed}");

        stopwatch.Restart();
        for (int i = 0; i < 1000; i++)
        {
            luaenv.DoString("StaticFunTest2('123')");
        }
        Debug.LogWarning($"耗時 {stopwatch.Elapsed}");

        stopwatch.Restart();
        for (int i = 0; i < 1000; i++)
        {
            luaenv.DoString("AddGenericList()");
        }
        Debug.LogWarning($"耗時 {stopwatch.Elapsed}");

        stopwatch.Restart();
        luaenv.Dispose();
    }
Ejemplo n.º 5
0
 private CLI.Result ExecuteByLine(CLI.Command cmd, int argFrom)
 {
     if (L == null)
     {
         L = new XLua.LuaEnv();
     }
     return(LuaReturnToCLIResult(L.DoString(cmd.Raw)));
 }
Ejemplo n.º 6
0
 public void test()
 {
     Manager.Instance.RemoveAllDaemon();
     ClearCommand();
     ClearText();
     L.GC();
     L.Dispose();
     L = new XLua.LuaEnv();
     L.DoString("require ('Main')");
     L.DoString("OnStart()");
 }
Ejemplo n.º 7
0
 // Use this for initialization
 void Start()
 {
     if (Instance == null)
     {
         Destroy(Instance);
     }
     Instance = this;
     if (L == null)
     {
         L = new XLua.LuaEnv();
         L.DoString("require ('Main')");
         L.DoString("OnStart()");
     }
 }
Ejemplo n.º 8
0
        public static void SetMainLuaEnv(LuaState env)
        {
            if (LuaDeepProfilerSetting.Instance.isDeepProfiler)
            {
                if (env != null)
                {
                    env.DoString(@"
BeginMikuSample = CS.MikuLuaProfiler.LuaProfiler.BeginSample
EndMikuSample = CS.MikuLuaProfiler.LuaProfiler.EndSample

function miku_unpack_return_value(...)
	EndMikuSample()
	return ...
end
");
                    HookSetup.HookLuaFuns();
                }
            }

            if (env == null)
            {
                HookSetup.Uninstall();
                LuaProfiler.mainL = IntPtr.Zero;
            }
        }
Ejemplo n.º 9
0
    public static void SaveString2()
    {
        TextAsset test = Resources.Load <TextAsset>("code/Skill001.lua");

        XLua.LuaEnv luaenv = new XLua.LuaEnv();
        //luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')");
        luaenv.DoString(test.text);
        luaenv.Dispose();
        Debug.Log(test);
        return;

        CustomSkill skill = SkillUtils.MakeCustomSkill("001");

        skill.id = 001;
        skill.Trigger(CustomSkill.TriggerType.fight);
        return;

        FormulaUtils.GetTowerExtraAttributes(false);
        return;

        for (int i = 0; i < 10; i++)
        {
            Debug.Log(UnityEngine.Random.Range(0, 0.5f));
        }
        return;

        //PlayerSQLPrefs.yzTowerLevel = 10;
        //PlayerSQLPrefs.yzTowerABSLevel = 10;
        PlayerOtherItem.ReduceItem(GameInstance.GameDatabase.otherItem[0].Id, 10);
    }
Ejemplo n.º 10
0
    void Start()
    {
        luaEnv = new XLua.LuaEnv();

        //luaEnv.DoString("print('hello world by execute string'");
        luaEnv.DoString("require 'LuaScript.helloworld'");
    }
Ejemplo n.º 11
0
    private void Awake()
    {
        luaEnv = new XLua.LuaEnv();

        scriptEnv = luaEnv.NewTable();

        LuaTable meta = luaEnv.NewTable();

        meta.Set("__index", luaEnv.Global);
        scriptEnv.SetMetaTable(meta);
        meta.Dispose();

        scriptEnv.Set("mono", this);
        foreach (var injection in injections)
        {
            scriptEnv.Set(injection.name, injection.value);
        }

        luaEnv.DoString(luaScript.text, "LuaBehaviour", scriptEnv);

        Action luaAwake = scriptEnv.Get <Action>("awake");

        scriptEnv.Get("start", out luaStart);
        scriptEnv.Get("update", out luaUpdate);
        scriptEnv.Get("fixedupdate", out luaFixedUpdate);
        scriptEnv.Get("ondestroy", out luaOnDestroy);

        if (luaAwake != null)
        {
            luaAwake();
        }
    }
Ejemplo n.º 12
0
 // Start is called before the first frame update
 void Start()
 {
     //Debug.Log("Hello world!");
     XLua.LuaEnv luaenv = new XLua.LuaEnv();
     luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')");
     luaenv.Dispose();
 }
Ejemplo n.º 13
0
 // Start is called before the first frame update
 void Start()
 {
     luaEnv = new XLua.LuaEnv();
     luaEnv.AddLoader((ref string filepath) =>
     {
         string path = PathDefines.luaDataPath + filepath + ".lua";
         return(File.ReadAllBytes(path));
     });
     luaEnv.DoString(GameMainLua.text, "GameMainLua");
 }
Ejemplo n.º 14
0
    private void Start()
    {
        var env = new XLua.LuaEnv();

        env.AddLoader(CustomLoad);

        env.DoString("print('this is CustomLoader'");

        env.Dispose();
        env = null;
    }
Ejemplo n.º 15
0
 public void reboot()
 {
     luaEnv.DoString(luaScript.text, "LuaBehaviour", scriptEnv);
     luaStart = null;
     scriptEnv.Get("start", out luaStart);
     scriptEnv.Get("update", out luaUpdate);
     scriptEnv.Get("fixedupdate", out luaFixedUpdate);
     scriptEnv.Get("ondestroy", out luaOnDestroy);
     if (luaStart != null)
     {
         luaStart();
     }
 }
Ejemplo n.º 16
0
    void Start()
    {
        luaEnv = new XLua.LuaEnv();
        luaEnv.DoString("CS.UnityEngine.Debug.Log('Hello Wold')");

        var max    = luaEnv.Global.GetInPath <LuaArgs>("math.max");
        var min    = luaEnv.Global.GetInPath <LuaArgs>("math.min");
        var random = luaEnv.Global.GetInPath <LuaArgs>("math.random");

        Debug.Log("max:" + max(32, 12));
        Debug.Log("min:" + min(32, 12));
        Debug.Log("random:" + random(1, 10));
    }
Ejemplo n.º 17
0
 private void SafeDoString(string scriptContent)
 {
     if (_luaEnv != null)
     {
         try
         {
             _luaEnv.DoString(scriptContent);
         }
         catch (System.Exception ex)
         {
             Debug.LogError("msg: " + $"xLua exception : {ex.Message}\n {ex.StackTrace}");
         }
     }
 }
Ejemplo n.º 18
0
    // Start is called before the first frame update
    private void Start()
    {
        var first  = new XLua.LuaEnv();
        var second = new XLua.LuaEnv();

        first.DoString("require LuaScript.somefolder.somescript");

        first.Global.Set <string, int>("A", 10);
        second.Global.Set <string, int>("B", 20);

        Debug.Log(first.Global.Get <int>("A"));      // 10
        //Debug.Log(first.Global.Get<int>("B"));      // Error


        first.DoString("print(A)");

        //Debug.Log(second.Global.Get<int>("A"));     // Error
        Debug.Log(second.Global.Get <int>("B"));     // 20


        first.Dispose();
        second.Dispose();
    }
Ejemplo n.º 19
0
    static void CompileLuaFile(XLua.LuaEnv L, string source, string output)
    {
        byte [] sbts = File.ReadAllBytes(source);
        sbts = FileUtils.utf8FiliterRom(sbts);

        int    ret = L.LuacExport(System.Text.Encoding.UTF8.GetString(sbts));
        IntPtr ptr = L.LuacGetBytes();

        if (ret <= 0)
        {
            UnityEngine.Debug.Log(L.DoString(sbts, source));
        }
        byte[] buffer = new byte[ret];
        Marshal.Copy(ptr, buffer, 0, ret);

        File.WriteAllBytes(output, buffer);
    }
Ejemplo n.º 20
0
    public void RunScriptMain()
    {
        if (luaEnv != null)
        {
            string path;

            if (useAssetBundle)
            {
                path = "assets/bytecode/main.bytes";
            }
            else
            {
                path = "Assets/" + XLua.LuaEnv.LuaRelativeDir + "/" + "Main.lua";
            }

            luaEnv.DoString(@"require 'Main'", path);
        }
    }
Ejemplo n.º 21
0
    void Start()
    {
        luaenv = new XLua.LuaEnv();
        luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')");
        //   luaenv.Dispose();


        var max = luaenv.Global.GetInPath <LuaMax>("math.max");

        Debug.Log("max:" + max(32, 12));

        Debug.Log("max:" + max(32, 100));
        Debug.Log("max:" + max(320, 12));

        curTime = DateTime.Now;

        StartCoroutine(SUpdate());
    }
Ejemplo n.º 22
0
    // Use this for initialization
    void Start()
    {
        XLua.LuaEnv luaenv = new XLua.LuaEnv();
        luaenv.DoString(@"
            CS.UnityEngine.Debug.Log('hello world')
            require 'socket'
            require 'pack'
            CS.UnityEngine.Debug.Log('哈哈')
            print(tonumber('40050.0'));
        ");

        var max = luaenv.Global.GetInPath <LuaMax>("math.max");

        Debug.Log("max:" + max(32, 12).ToString());
        max = null;

        luaenv.Dispose();
    }
Ejemplo n.º 23
0
 void _ReloadLua()
 {
     if (_env != null)
     {
         if (LuaEntry.Dispose != null)
         {
             LuaEntry.Dispose();
             //_env.DoString(@"print('随便再执行一行lua代码,重新创建env就不会报错')");
         }
         _env.Dispose();
         _env = null;
     }
     _env = new XLua.LuaEnv();
     _env.DoString(@"require 'main'");
     if (LuaEntry.Init != null)
     {
         LuaEntry.Init();
     }
 }
Ejemplo n.º 24
0
        // second step
        public virtual void StartScript()
        {
            _luaenv = new XLua.LuaEnv();
            _luaenv.AddBuildin("cjson", Maria.Lua.BuildInInit.LoadCJson);
            _luaenv.AddBuildin("lpeg", Maria.Lua.BuildInInit.LoadLpeg);
            _luaenv.AddBuildin("sproto.core", Maria.Lua.BuildInInit.LoadSprotoCore);
            _luaenv.AddBuildin("ball", Maria.Lua.BuildInInit.LoadBall);
            _luaenv.AddLoader((ref string filepath) => {
                UnityEngine.Debug.LogFormat("LUA custom loader {0}", filepath);

                string[] xpaths = filepath.Split(new char[] { '.' });
                string path     = "xlua/src";
                int idx         = 0;
                while (idx + 1 < xpaths.Length)
                {
                    path += "/";
                    path += xpaths[idx];
                    idx++;
                }

                TextAsset file = ABLoader.current.LoadAsset <TextAsset>(path, xpaths[idx] + ".lua");
                if (file != null)
                {
                    return(file.bytes);
                }
                else
                {
                    file = ABLoader.current.LoadAsset <TextAsset>(path + "/lualib", xpaths[idx] + ".lua");
                    if (file != null)
                    {
                        return(file.bytes);
                    }
                    return(null);
                }
            });
            _luaenv.DoString(@" require 'main' ");
            Main main = _luaenv.Global.Get <Main>("main");

            Bacon.Lua.ILuaPool pool = main();
            Maria.Lua.LuaPool.Instance.Cache <Bacon.Lua.ILuaPool>(pool);
        }
Ejemplo n.º 25
0
    void Start()
    {
        mState = new XLua.LuaEnv();

        // xLuaHook important ------------------
        // open xlua debug hook library
        XLua.LuaHook.OpenDebug(mState.rawL);

        mState.AddLoader(GetDecodeContent);
#if UNITY_EDITOR
        AutoAddSearchPath(Application.dataPath + "/LuaScripts");

        // xLuaHook important ------------------
        // add xlua debug hook path
        AutoAddSearchPath(Application.dataPath + "/XLuaHook/LuaScripts");
#endif

        mState.DoString("require(\"Main\")");
        mLuaUpdate  = mState.Global.Get <LuaUpdateDelegate>("GlobalUpdate");
        mLuaInit    = mState.Global.Get <LuaInitDelegate>("GlobalInit");
        mLuaDestroy = mState.Global.Get <LuaDestroyDelegate>("GlobalDestroy");

        mLuaInit();
    }
Ejemplo n.º 26
0
        static int _m_DoString(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                XLua.LuaEnv gen_to_be_invoked = (XLua.LuaEnv)translator.FastGetCSObj(L, 1);


                int gen_param_count = LuaAPI.lua_gettop(L);

                if (gen_param_count == 4 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TSTRING) && (LuaAPI.lua_isnil(L, 4) || LuaAPI.lua_type(L, 4) == LuaTypes.LUA_TTABLE))
                {
                    byte[]        _chunk     = LuaAPI.lua_tobytes(L, 2);
                    string        _chunkName = LuaAPI.lua_tostring(L, 3);
                    XLua.LuaTable _env       = (XLua.LuaTable)translator.GetObject(L, 4, typeof(XLua.LuaTable));

                    object[] gen_ret = gen_to_be_invoked.DoString(_chunk, _chunkName, _env);
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 3 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TSTRING))
                {
                    byte[] _chunk     = LuaAPI.lua_tobytes(L, 2);
                    string _chunkName = LuaAPI.lua_tostring(L, 3);

                    object[] gen_ret = gen_to_be_invoked.DoString(_chunk, _chunkName);
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 2 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING))
                {
                    byte[] _chunk = LuaAPI.lua_tobytes(L, 2);

                    object[] gen_ret = gen_to_be_invoked.DoString(_chunk);
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 4 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TSTRING) && (LuaAPI.lua_isnil(L, 4) || LuaAPI.lua_type(L, 4) == LuaTypes.LUA_TTABLE))
                {
                    string        _chunk     = LuaAPI.lua_tostring(L, 2);
                    string        _chunkName = LuaAPI.lua_tostring(L, 3);
                    XLua.LuaTable _env       = (XLua.LuaTable)translator.GetObject(L, 4, typeof(XLua.LuaTable));

                    object[] gen_ret = gen_to_be_invoked.DoString(_chunk, _chunkName, _env);
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 3 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING) && (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TSTRING))
                {
                    string _chunk     = LuaAPI.lua_tostring(L, 2);
                    string _chunkName = LuaAPI.lua_tostring(L, 3);

                    object[] gen_ret = gen_to_be_invoked.DoString(_chunk, _chunkName);
                    translator.Push(L, gen_ret);



                    return(1);
                }
                if (gen_param_count == 2 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING))
                {
                    string _chunk = LuaAPI.lua_tostring(L, 2);

                    object[] gen_ret = gen_to_be_invoked.DoString(_chunk);
                    translator.Push(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }

            return(LuaAPI.luaL_error(L, "invalid arguments to XLua.LuaEnv.DoString!"));
        }
Ejemplo n.º 27
0
 public static void LoadLua(string text)
 {
     Log.LogColor("lua 加载 文件 " + text);
     XLua.LuaEnv lua = new XLua.LuaEnv();
     lua.DoString(text);
 }
Ejemplo n.º 28
0
        public Application(Maria.Util.App app)
        {
            _app    = app;
            _tiSync = new TimeSync();
            _tiSync.LocalTime();
            _lastTi = _tiSync.LocalTime();

#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
            //_cotype = CoType.THREAD;
            _cotype = CoType.CO;
#elif UNITY_IOS || UNITY_ANDROID
            _cotype = CoType.CO;
#endif
            if (_cotype == CoType.THREAD)
            {
                _semaphore           = new Semaphore(1, 1);
                _worker              = new Thread(new ThreadStart(Worker));
                _worker.IsBackground = true;
                _worker.Start();
                UnityEngine.Debug.LogWarning("create thread success.");
            }
            else
            {
                UnityEngine.Debug.LogWarning("create co success.");
            }
            _luaenv = new XLua.LuaEnv();
            _luaenv.AddBuildin("cjson", XLua.LuaDLL.Lua.LoadCJson);
            _luaenv.AddBuildin("lpeg", XLua.LuaDLL.Lua.LoadLpeg);
            _luaenv.AddBuildin("sproto.core", XLua.LuaDLL.Lua.LoadSprotoCore);
            _luaenv.AddLoader((ref string filepath) => {
                UnityEngine.Debug.LogFormat("LUA custom loader {0}", filepath);

                string[] xpaths = filepath.Split(new char[] { '.' });
                string path     = "xlua/src";
                int idx         = 0;
                while (idx + 1 < xpaths.Length)
                {
                    path += "/";
                    path += xpaths[idx];
                    idx++;
                }

                TextAsset file = ABLoader.current.LoadAsset <TextAsset>(path, xpaths[idx] + ".lua");
                if (file != null)
                {
                    return(file.bytes);
                }
                else
                {
                    file = ABLoader.current.LoadAsset <TextAsset>(path + "/lualib", xpaths[idx] + ".lua");
                    if (file != null)
                    {
                        return(file.bytes);
                    }
                    return(null);
                }
            });
            _luaenv.DoString(@"
require 'main'
");
        }
Ejemplo n.º 29
0
 public void DoFile(string _fileName)
 {
     luaEnv.DoString(string.Format("require '{0}'", _fileName));
 }
Ejemplo n.º 30
0
 public void DoString(string content)
 {
     LuaEnv.DoString(content);
 }