topameng/tolua

LuaState下GetFunction使用的缓存存在一个BUG

syw-Mjollner opened this issue · 1 comments

//修改示例里的CallLuaFunction ,稳定重现BUG
//点击DoString,再点Click,再点DoString,再点Click,这个时候的输出showOrderWnd MoneyValue = 0,原因是函数调用的缓存,想不好如何修改
using UnityEngine;
using System.Collections;
using LuaInterface;
using System;

public class CallLuaFunction : MonoBehaviour 
{
    private string script =
        @"  PaymentWnd = {}
            local MoneyValue = 0

            function PaymentWnd.ClickBtnCharge()
                MoneyValue = 618
                print('ClickBtnCharge MoneyValue = '..MoneyValue)
                PaymentWnd.showOrderWnd()
            end

            function PaymentWnd.showOrderWnd()
                print('showOrderWnd MoneyValue = '..MoneyValue)
            end
        ";

    LuaFunction luaFunc = null;
    LuaState lua = null;
    string tips = null;
	
	void Start () 
    {
#if UNITY_5 || UNITY_2017 || UNITY_2018
        Application.logMessageReceived += ShowTips;
#else
        Application.RegisterLogCallback(ShowTips);
#endif
        new LuaResLoader();
        lua = new LuaState();
        lua.Start();
        DelegateFactory.Init();

        lua.CheckTop();
	}

    void ShowTips(string msg, string stackTrace, LogType type)
    {
        tips += msg;
        tips += "\r\n";
    }

#if !TEST_GC
    void OnGUI()
    {
        GUI.Label(new Rect(Screen.width / 2 - 200, Screen.height / 2 - 150, 400, 300), tips);
        if (GUI.Button(new Rect(50, 50, 120, 45), "DoString"))
        {
            lua.DoString(script);
        }
        if (GUI.Button(new Rect(50, 100, 120, 45), "Click"))
        {
            //Get the function object
            luaFunc = lua.GetFunction("PaymentWnd.ClickBtnCharge");

            if (luaFunc != null)
            {
                //int num = luaFunc.Invoke<int>();
                //Debugger.Log("generic call return: {0}", num);

                CallFunc();
                //Debugger.Log("expansion call return: {0}", num);

                //Func<int> Func = luaFunc.ToDelegate<Func<int>>();
                //num = Func();
                //Debugger.Log("Delegate call return: {0}", num);

                //num = lua.Invoke<int>("PaymentWnd.ClickBtnCharge", true);
                //Debugger.Log("luastate call return: {0}", num);
            }
        }
    }
#endif

    void OnDestroy()
    {
        if (luaFunc != null)
        {
            luaFunc.Dispose();
            luaFunc = null;
        }

        lua.Dispose();
        lua = null;

#if UNITY_5 || UNITY_2017 || UNITY_2018
        Application.logMessageReceived -= ShowTips;
#else
        Application.RegisterLogCallback(null);
#endif
    }

    void CallFunc()
    {        
        luaFunc.BeginPCall(); 
        luaFunc.PCall();
        luaFunc.EndPCall();      
    }
}

void CallFunc()
{
luaFunc.BeginPCall();
luaFunc.PCall();
luaFunc.EndPCall();
luaFunc.Dispose();

}