Example #1
0
 public static void OnStart()
 {
     if (wasExecuted)
     {
         script.Call(script.Globals.Get("OnStart"));
     }
 }
Example #2
0
        public void CompileAndRunString()
        {
            state = new Lua();

            LuaStatus result = state.LoadString("x=1");

            stackDump(state);

            state.Call(0, 0);
            stackDump(state);

            result = state.LoadString("1");
            stackDump(state);

            state.PCall(0, 0, 0);
            stackDump(state);

            result = state.LoadString("print(x)"); // stdout??
            stackDump(state);

            state.Call(0, 0);
            stackDump(state);

            state.Close();
        }
Example #3
0
    // 开发模式,直接源文件DoFile
    public static void DoAllLuaFileDev()
    {
        HashSet <string> set = new HashSet <string>();

        for (int i = 0; i < firstLoadFiles.Length; ++i)
        {
            set.Add(firstLoadFiles[i]);
        }

        DirectoryInfo dir = new DirectoryInfo(LuaConst.luaDir);

        AddP27SearchPath(); // Add 之后 直接DoFile 名字(不带后缀)

        FileInfo[] files = dir.GetFiles("*.lua", SearchOption.AllDirectories);

        // 加载firstLoad
        for (int i = 0; i < firstLoadFiles.Length; ++i)
        {
            Lua.state.DoFile(firstLoadFiles[i]);
        }

        // 加载其他
        for (int i = 0; i < files.Length; ++i)
        {
            string luafileName = PathUtil.GetFileNameWithoutExtension(files[i].FullName);
            if (!set.Contains(luafileName))
            {
                Lua.state.DoFile(luafileName);
            }
        }

        Lua.Call("Main.OnInitOK");   //初始化完成
    }
Example #4
0
    // AssetBundle中加载lua文件,运行时。
    public static void DoAllLuaFile(AssetBundleRef luaAbr)
    {
        UnityEngine.Object[] luaFiles = luaAbr.LoadAllAssets();

        HashSet <string> set = new HashSet <string>();

        for (int i = 0; i < firstLoadFiles.Length; ++i)
        {
            set.Add(firstLoadFiles[i].ToLower());
        }
        TextAsset t;

        // 先加载firstLoad
        for (int i = 0; i < luaFiles.Length; i++)
        {
            string pureName = PathUtil.GetFileNameWithoutExtension(luaFiles[i].name);
            if (set.Contains(pureName))
            {
                t = luaFiles[i] as TextAsset;
                Lua.state.DoString(t.text);
            }
        }

        // 加载非firstLoad
        for (int i = 0; i < luaFiles.Length; i++)
        {
            string pureName = PathUtil.GetFileNameWithoutExtension(luaFiles[i].name);
            if (!set.Contains(pureName))
            {
                t = luaFiles[i] as TextAsset;
                Lua.state.DoString(t.text);
            }
        }
        Lua.Call("Main.OnInitOK");   //初始化完成
    }
Example #5
0
 bool LoadInitFuncToInstanceTable(Lua L)
 {
     if (_InitChunk == null || _InitChunk.Length == 0)
     {
         // remove _Init func
         Api.lua_rawgeti(L, Api.LUA_REGISTRYINDEX, luaBehaviourRef);
         Api.lua_pushnil(L);
         Api.lua_setfield(L, -2, "_Init");
         return(false);
     }
     try
     {
         Api.lua_rawgeti(L, Api.LUA_REGISTRYINDEX, luaBehaviourRef);
         L.LoadChunk(_InitChunk, scriptName + "_Init");
         L.Call(0, 1);                 // run loaded chunk
         Api.lua_setfield(L, -2, "_Init");
         Api.lua_pop(L, 1);            // pop behaviour table
         return(true);
     }
     catch (Exception e)
     {
         Debug.LogError(e.Message);
     }
     return(false);
 }
Example #6
0
        static void Main(string[] args)
        {
            Console.Title = "LuaBintils Test";

            /*
             * {
             *      LuaChunk LC = new LuaChunk("luac.out");
             *      Console.WriteLine(LC.Functions[0].ToString2());
             *      Console.ReadLine();
             *      return;
             * }
             * //*/

            LuaChunk MainChunk = new LuaChunk();

            Lua L = new Lua(MainChunk.CreateFunction(0, "@luac.lua"));

            L.Load("Hello World!");
            L.GetGlobal("print");
            L.Swap(0, 1);
            L.Call(0, 2, 1);
            L.Return(0, 1);

            L.Func.MaxStackSize = 50;
            MainChunk.Save("lua.out");

            Console.WriteLine(MainChunk.Functions[0]);
            Console.ReadLine();
        }
    public virtual void Start()
    {
        this.name = this.name.Replace("(Clone)", "");

        if (exporter == null)
        {
            string   scriptName = name + "View";
            object[] obj        = Lua.Call(scriptName, param);
            LuaController = obj[0] as LuaTable;
        }
        else
        {
            LuaController = exporter.InitLuaController(param);
            LuaController["gameObject"] = this.gameObject;
            LuaController["transform"]  = transform;
        }

        LuaController["this"] = this;

        UILayer layer = this.GetComponent <UILayer>();

        if (layer != null)
        {
            LuaController["layer"] = layer;
        }

        updateFunc = LuaController["Update"] as LuaFunction;
        CallLuaMethod("Start", this, gameObject);
    }
 public void OnDestroyed(Tile tile)
 {
     if (destroyedFunction == null)
     {
         return;
     }
     Lua.Call(destroyedFunction, tile);
 }
Example #9
0
        /// <summary>
        /// Calls the <see cref="LuaFunction"/> with the given arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <returns>The results.</returns>
        /// <exception cref="ArgumentException">
        /// One of the supplied arguments is a <see cref="LuaReference"/> which is tied to a different <see cref="Lua"/> environment.
        /// </exception>
        /// <exception cref="ArgumentNullException"><paramref name="args"/> is <c>null</c>.</exception>
        /// <exception cref="LuaException">A Lua error occurs.</exception>
        public object[] Call(params object[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            PushOnto(Lua.MainState);
            return(Lua.Call(args));
        }
    private void Trigger()
    {
        if (executionActions != null)
        {
            Lua.Call(executionActions.ToArray(), this);
        }

        if (!CanRepeat && !infiniteRepeats)
        {
            executed = true;
        }
    }
Example #11
0
        /// <summary>
        /// Resumes the <see cref="LuaThread"/> with the given arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <returns>The results.</returns>
        /// <exception cref="ArgumentException">
        /// One of the supplied arguments is a <see cref="LuaReference"/> which is tied to a different <see cref="Lua"/> environment.
        /// </exception>
        /// <exception cref="ArgumentNullException"><paramref name="args"/> is <c>null</c>.</exception>
        /// <exception cref="InvalidOperationException">The <see cref="LuaThread"/> cannot be resumed.</exception>
        /// <exception cref="LuaException">A Lua error occurs.</exception>
        public object[] Resume(params object[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }
            if (!CanResume)
            {
                throw new InvalidOperationException("Thread cannot be resumed.");
            }

            return(Lua.Call(args, _threadState, true));
        }
    public void Update()
    {
        if (executed || MaxRepeats > 0 && repeatAmount >= MaxRepeats)
        {
            return;
        }
        if (preconditions.Any(precondition => !Lua.Call(precondition, this, Time.deltaTime).Boolean))
        {
            return;
        }

        if (!infiniteRepeats)
        {
            repeatAmount++;
        }
        Trigger();
    }
Example #13
0
        public void PanicError() // PANIC: unprotected error in call to Lua API (attempt to call a string value)
        {
            state = new Lua();

            LuaFunction oldPanic = state.AtPanic(MyPanicFunc);

            stackDump(state);

            LuaStatus result = state.LoadString("1");

            stackDump(state);

            try
            {
                state.Call(0, 0);
                Assert.Fail("Shoudln't go so far");
            }
            catch (MyPanicException ex)
            { }
            stackDump(state);

            state.Close();
        }
Example #14
0
 void RunInitFuncOnInstanceTable(Lua L)
 {
     Api.lua_rawgeti(L, Api.LUA_REGISTRYINDEX, luaBehaviourRef);
     // Behaviour._Init hides Script._Init
     Api.lua_getfield(L, -1, "_Init");
     if (Api.lua_isfunction(L, -1))
     {
         Api.lua_pushvalue(L, -2);
         try
         {
             L.Call(1, 0);
         }
         catch (Exception e)
         {
             Debug.LogErrorFormat("{0}._Init failed: {1}.", scriptName, e.Message);
         }
     }
     else
     {
         Api.lua_pop(L, 1);         // pop non-function
     }
     Api.lua_pop(L, 1);             // pop behaviour table
 }
Example #15
0
        void Awake()
        {
            if (L == null || !L.valid)
            {
                Debug.LogError("Call LuaBehaviour.SetLua first.");
                return;
            }

            if (string.IsNullOrEmpty(scriptName))
            {
                Debug.LogWarning("LuaBehaviour with empty scriptName.");
                return;
            }

            // make	instance
            handleToThis = L.MakeRefTo(this);

            Api.lua_newtable(L);
            // stack: instance table
            luaBehaviourRef = L.MakeRefAt(-1);

            // meta
            Api.lua_createtable(L, 1, 1);
            // stack: instance table, meta

            L.PushRef(handleToThis);
            Api.lua_rawseti(L, -2, 1);             // meta[1] = behaviour (this)

            // TODO: can be	opt, each Script take its own meta for LuaBehaviour
            // load	class
            Api.luaL_requiref(L, scriptName, Lua.LoadScript1, 0);
            // stack: instance table, meta, script table

            if (Api.lua_istable(L, -1))             // set metatable and bind messages
            {
                // stack: behaviour table, meta, script table
                L.DoString("return function(be, script)\n" +
                           "  return function(t, key)\n" +
                           "    local val = script[key]\n" +
                           "    if type(val) == 'nil' then val = be[key] end\n" +
                           "    return val\n" +
                           "  end\n" +
                           "end", 1, "LuaBehaviour_GetMetaIndexFunction");
                L.PushRef(handleToThis);
                Api.lua_pushvalue(L, -3);
                L.Call(2, 1);
                // stack: instance table, meta, script table, index function
                Api.lua_setfield(L, -3, "__index");
                // stack: instance table, meta, script table
                Api.lua_insert(L, -3);
                // stack: script table, instance table, meta
                Api.lua_setmetatable(L, -2);
                // stack: script table, instance table

                // check message
                for (Message i = Message.Awake; i < Message._Count; ++i)
                {
                    Api.lua_pushstring(L, i.ToString());
                    // stack: script table, instance table, key
                    Api.lua_gettable(L, -3);
                    // stack: script table, instance table, function?
                    if (Api.lua_isfunction(L, -1))
                    {
                        messageFlag        = messageFlag | MakeFlag(i);
                        messageRef[(int)i] = Api.luaL_ref(L, -2);                         // func pops, and make ref in behaviour table
                    }
                    else
                    {
                        Api.lua_pop(L, 1);                         // pop field
                    }
                    // stack: script table,	instance table
                }

                // choose script
                ulong flag          = messageFlag & (MakeFlag(Message.Update) | MakeFlag(Message.FixedUpdate) | MakeFlag(Message.LateUpdate));
                var   componentType = Type.GetType("lua.LuaInstanceBehaviour" + flag.ToString());
                instanceBehaviours.Add(gameObject.AddComponent(componentType) as LuaInstanceBehaviour0);

                flag = messageFlag & (MakeFlag(Message.OnCollisionEnter) | MakeFlag(Message.OnCollisionExit));
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaCollisionBehaviour>());
                }
                flag = messageFlag & MakeFlag(Message.OnCollisionStay);
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaCollisionStayBehaviour>());
                }

                flag = messageFlag & (MakeFlag(Message.OnCollisionEnter2D) | MakeFlag(Message.OnCollisionExit2D));
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaCollisionBehaviour2D>());
                }
                flag = messageFlag & MakeFlag(Message.OnCollisionStay2D);
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaCollisionStayBehaviour2D>());
                }

                flag = messageFlag & (MakeFlag(Message.OnTriggerEnter) | MakeFlag(Message.OnTriggerEnter));
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaTriggerBehaviour>());
                }
                flag = messageFlag & MakeFlag(Message.OnTriggerStay);
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaTriggerStayBehaviour>());
                }


                flag = messageFlag & (MakeFlag(Message.OnTriggerEnter2D) | MakeFlag(Message.OnTriggerEnter2D));
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaTriggerBehaviour2D>());
                }
                flag = messageFlag & MakeFlag(Message.OnTriggerStay2D);
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaTriggerStayBehaviour2D>());
                }

                flag = messageFlag
                       & (MakeFlag(Message.Event_PointerClick)
                          | MakeFlag(Message.Event_PointerUp)
                          | MakeFlag(Message.Event_PointerDown)
                          | MakeFlag(Message.Event_PointerEnter)
                          | MakeFlag(Message.Event_PointerExit));
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaPointerEventHander>());
                }

                flag = messageFlag & (MakeFlag(Message.Event_Drag) | MakeFlag(Message.Event_BeginDrag) | MakeFlag(Message.Event_EndDrag));
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaDragEventHandler>());
                }

                flag = messageFlag & (MakeFlag(Message.Event_GestureTwoFingerBegin) | MakeFlag(Message.Event_GestureTwoFingerMove) | MakeFlag(Message.Event_GestureTwoFingerEnd));
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaGestureTwoFingerEventHandler>());
                }

                flag = messageFlag & MakeFlag(Message.OnLowMemory);
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaLowMemoryHandler>());
                }

                flag = messageFlag & (MakeFlag(Message.OnDrawGizmos) | MakeFlag(Message.OnDrawGizmosSelected) | MakeFlag(Message.OnGUI));
                if (flag != 0)
                {
                    instanceBehaviours.Add(gameObject.AddComponent <LuaMiscBehaviour>());
                }

                Api.lua_pop(L, 2);                 // pop instance table, script table

                scriptLoaded_ = true;
            }
            else
            {
                Api.lua_pop(L, 3);                 // pop instance table, meta, script table
            }

            // stack: (*empty)

            if (scriptLoaded_)
            {
                // load	_Init from serialized version
                LoadInitFuncToInstanceTable(L);
                RunInitFuncOnInstanceTable(L);

                // Awake Lua script
                for (int i = 0; i < instanceBehaviours.Count; ++i)
                {
                    instanceBehaviours[i].hideFlags = HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor | HideFlags.NotEditable;
                    instanceBehaviours[i].SetLuaBehaviour(this);
                    instanceBehaviours[i].enabled = false;
                }
                SendLuaMessage(LuaBehaviour.Message.Awake);                 // Awake Lua Script
            }
            else
            {
                Debug.LogWarningFormat("No Lua script running with {0}.", gameObject.name);
            }
        }
Example #16
0
        void Reload()
        {
            var lb = target as LuaBehaviour;

            if (lb == null)
            {
                initChunkLoadFailed = true;
                if (Application.isPlaying)
                {
                    reason = "Unity is Playing";
                }
                else
                {
                    reason = "Unknown";
                }
                return;
            }

            if (string.IsNullOrEmpty(lb.scriptName))
            {
                return;
            }

            noInitFunc          = false;
            initChunkLoadFailed = false;
            reason = string.Empty;

            // load from script
            Api.lua_pushcclosure(L, Lua.LoadScript1InEditor, 0);
            Api.lua_pushstring(L, lb.scriptName);
            try
            {
                L.Call(1, Api.LUA_MULTRET);
            }
            catch (Exception e)
            {
                initChunkLoadFailed = true;
                reason = e.Message;
                return;
            }

            // stack: table, scriptPath

            if (!Api.lua_istable(L, -2))
            {
                initChunkLoadFailed = true;
                reason = string.Format("Needs behaviour table returned from {0}.lua", lb.scriptName);
                return;
            }

            if (!Api.lua_isstring(L, -1))
            {
                initChunkLoadFailed = true;
                reason = "Internal error. Lua.LoadScript2 should return behaviour table and loaded path.";
                return;
            }

            lb.scriptPath = Api.lua_tostring(L, -1);
            Api.lua_pop(L, 1);

            // stack: table
            var luaType = Api.lua_getfield(L, -1, "_doc");

            if (luaType == Api.LUA_TSTRING)
            {
                docString = Api.lua_tostring(L, -1);
            }
            Api.lua_pop(L, 1);

            luaType = Api.lua_getfield(L, -1, "_Init");
            Api.lua_remove(L, -2);             // keep _Init, remove table
            if (luaType != Api.LUA_TFUNCTION)
            {
                noInitFunc = true;
                Api.lua_pop(L, 1);                 // pop func
                SetInitChunkByString(lb, null);
                keys   = null;
                values = null;
                return;
            }

            // stack: func

            // call Script._Init on instance
            Api.lua_newtable(L);                                        // oringal table
            // stack: func, table
            Api.lua_pushvalue(L, -1);                                   // push again, stack: func, table, table
            var refToOriginal = Api.luaL_ref(L, Api.LUA_REGISTRYINDEX); // stack: func, table

            try
            {
                L.Call(1, 0);
            }
            catch (Exception e)
            {
                Api.luaL_unref(L, Api.LUA_REGISTRYINDEX, refToOriginal);
                initChunkLoadFailed = true;
                reason = e.Message;
                return;
            }

            // stack: *empty*

            if (lb.IsInitFuncDumped())
            {
                Api.lua_newtable(L);                 // new table for loading valued from dumpped _Init function
                // stack: table
                try
                {
                    L.LoadChunk(lb.GetInitChunk(), lb.scriptName + "_Init_Editor");
                    // stack: table, loaded chunk (emits _Init function)
                    L.Call(0, 1);                     // run loaded chunk
                    // stack: table, func
                    Api.lua_pushvalue(L, -2);
                    // stack: table, func, table
                    L.Call(1, 0);
                }
                catch (Exception e)
                {
                    Api.lua_pop(L, 1);                     // pop table
                    Api.luaL_unref(L, Api.LUA_REGISTRYINDEX, refToOriginal);
                    initChunkLoadFailed = true;
                    reason = e.Message;
                    return;
                }

                // stack: table

                // merge two tables
                // -1: deserialized values

                Api.luaL_dostring(L, mergeFunction);
                luaType = Api.lua_getglobal(L, "merge");
                // stack: table, func
                Api.lua_rawgeti(L, Api.LUA_REGISTRYINDEX, refToOriginal);
                // stack: table, func, original table
                Api.lua_pushvalue(L, -3);
                // stack: table, func, original table, table
                Api.lua_remove(L, -4);
                // stack: func, original table, table

                try
                {
                    L.Call(2, 1);
                }
                catch (Exception e)
                {
                    Api.luaL_unref(L, Api.LUA_REGISTRYINDEX, refToOriginal);
                    initChunkLoadFailed = true;
                    reason = e.Message;
                    return;
                }

                // stack: merged table
            }
            else
            {
                Api.lua_rawgeti(L, Api.LUA_REGISTRYINDEX, refToOriginal);
                Api.luaL_unref(L, Api.LUA_REGISTRYINDEX, refToOriginal);
                // stack: orignal table
            }


            // prepare to show on Inspector
            keys   = new List <string>();
            values = new List <object>();
            // iterate table on stack
            Api.lua_pushnil(L);
            while (Api.lua_next(L, -2) != 0)
            {
                var key   = Api.lua_tostring(L, -2);
                var value = L.ValueAt(-1);
                keys.Add(key);
                values.Add(value);
                Api.lua_pop(L, 1);
            }
            Api.lua_pop(L, 1);             // pop table
            // stack: *empty*

            int[] sortedIndex = new int[keys.Count];
            for (int i = 0; i < sortedIndex.Length; ++i)
            {
                sortedIndex[i] = i;
            }
            System.Array.Sort(sortedIndex, (a, b) => keys[a].CompareTo(keys[b]));
            keys.Sort();
            var newValues = new List <object>();

            for (int i = 0; i < values.Count; ++i)
            {
                newValues.Add(values[sortedIndex[i]]);
            }
            values = newValues;

            if (lb.IsInitFuncDumped())
            {
                // dump again, in case of Script._Init and Behaviour._Init being merged.
                DumpInitValues();
            }
            serializedObject.Update();
        }
Example #17
0
/*    void Start()
 *  {
 *
 *      lastMsgShowTime = Time.time;
 *
 *      //for (int i = 0; i < maxPickMsg; ++i)
 *      //{
 *      //    GameObject go = GameObject.Instantiate(msgObj, Vector3.zero, Quaternion.identity) as GameObject;
 *      //    go.SetActive(false);
 *      //    go.transform.SetParent(this.transform);
 *      //    go.transform.localScale = new Vector3(1, 1, 1);
 *      //    list.Add(go);
 *      //}
 *  }*/


    #region 显示信息



    /* 显示消息文本
     * SysInfoData msgData = SysInfoData.Init();
     * msgData.type = SysInfoType.Text;
     * msgData.text = msg;
     * msgList.Enqueue(msgData);
     *
     */
    public void ShowMsg(string msg)
    {
        Lua.Call <string>("ui.showMsg", msg);
    }
Example #18
0
 public void Execute(WorldData worldData)
 {
     Lua.Call(rootProcess, worldData.Width, worldData.Height);
 }