Unity3D C#调用UniLua

来源:互联网 发布:尼采知乎 编辑:程序博客网 时间:2024/06/05 07:21

Test.CS

using UnityEngine;using System.Collections;using UniLua;using System;public class Test : MonoBehaviour{    public string LuaScriptFile = "framework/fuck.lua";    private ILuaState Lua;    private int AwakeRef;    private int Fuck;    void Awake()    {        if (Lua == null)        {            Lua = LuaAPI.NewState();            Lua.L_OpenLibs();            var status = Lua.L_DoFile(LuaScriptFile);            if (status != ThreadStatus.LUA_OK)            {                throw new Exception(Lua.ToString(-1));            }            if (!Lua.IsTable(-1))            {                throw new Exception("framework main's return value is not a table");            }            AwakeRef = StoreMethod("awake");            Fuck = StoreMethod("fuck");            Lua.Pop(1);            Debug.Log("Lua Init Done");            CallMethod(AwakeRef);        }    }    // Use this for initialization    void Start()    {    }    void OnGUI()    {        if (GUI.Button(new Rect(0, 0, 200, 20), "FUCK"))        {            CallMethod(Fuck);        }    }    private int StoreMethod(string name)    {        Lua.GetField(-1, name);        if (!Lua.IsFunction(-1))        {            throw new Exception(string.Format(                "method {0} not found!", name));        }        return Lua.L_Ref(LuaDef.LUA_REGISTRYINDEX);    }    private void CallMethod(int funcRef)    {        Lua.RawGetI(LuaDef.LUA_REGISTRYINDEX, funcRef);        // insert `traceback' function        var b = Lua.GetTop();        Lua.PushCSharpFunction(Traceback);        Lua.Insert(b);        var status = Lua.PCall(0, 0, b);        if (status != ThreadStatus.LUA_OK)        {            Debug.LogError(Lua.ToString(-1));        }        // remove `traceback' function        Lua.Remove(b);    }    private static int Traceback(ILuaState lua)    {        var msg = lua.ToString(1);        if (msg != null)        {            lua.L_Traceback(lua, msg, 1);        }        // is there an error object?        else if (!lua.IsNoneOrNil(1))        {            // try its `tostring' metamethod            if (!lua.L_CallMeta(1, "__tostring"))            {                lua.PushString("(no error message)");            }        }        return 1;    }}

fuck.lua

local function awake()    print("---- awakefuck ----")endlocal function fuck()print("FUCK")endreturn {awake = awake,fuck = fuck,}

效果



0 0