tolua集成lua-protobuf库

在tolua基础上,为了方便使用proto3,这里集成了lua-protobuf库!
十分感谢两位开源库的大大,tolua的蒙大和lua-protobuf的Xavier!在两位的github上有q群的联系方式,欢迎加群交流!
有什么问题也可以在我blog下留言!
本文基于win7x64,unity2017.4,tolua当前最新版本,tolua_runtime当前最新版本,lua-protobuf当前最新版本编写

一丶编译tolua库

资源下载:
tolua_runtime
https://github.com/topameng/tolua_runtime
NDK 版本:android-ndk-r10e 默认安装到 D:/android-ndk-r10e
https://dl.google.com/android/repository/android-ndk-r10e-windows-x86_64.zip
配置好的Msys2下载
https://pan.baidu.com/s/1c2JzvDQ
lua-protobuf
https://github.com/starwing/lua-protobuf

正文:
1.将lua-protobuf工程中的pb.c和pb.h拷贝到tolua_runtime根目录,覆盖pb.c
编译各平台dll
https://www.jianshu.com/p/5a35602adef8?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
2.编译后tolua_runtime下的Plugins文件夹拷贝至tolua文件夹下同名覆盖

问题:
1.NDK路径问题
在tolua_runtime中
build_arm.sh
build_arm64.sh
build_x86.sh
link_arm64.bat
中ndk路径需要和你电脑上ndk的目录一致!
2.群友的总结
(感谢 lua-protobuf交流群 - 潜水的小懒猫 么么哒!)
a.在mac上替换tolua.bundle文件时,需要重启unity,不然无法读取pb
b.在编译mac时,会提示i386架构被弃用,需删掉,将不再支持iPhone5以下机型
(如果执行build_osx.sh时提示不在支持32位,请打开macnojit 在build Setting移除i386的支持即可)
c.在发布ios时,要删除tolua目录下的pb.c文件,不然编译不通过
d.如果执行.sh提示权限不足 可以在终端执行:chmod 777 tolua根目录 然后再次执行.sh脚本即可
3.编译工具的一些说明
Msys2下载后,在其根目录有mingw32_shell.bat和mingw64_shell.bat用来分别开启32位和64位 Msys
32位用于执行tolua_runtime中的build_arm.sh、build_win32.sh、build_x86.sh
64位用于执行tolua_runtime中的build_arm64.sh、build_win64.sh
build_ios.sh、build_osx.sh需要在mac 下执行
build_ubuntu.sh需要在linux下执行(不使用linux开发,不要要编译)
4…sh怎么执行?
在各终端(PC用Msys,mac和linux都是自带)进入.sh脚本所在目录 ./xxx.sh
tolua集成lua-protobuf库_第1张图片
5.各种.sh执行中的Error
一定要注意,有错误就要修改,要不打出的dll不保证好用!Error的种类有很多,可以参见出错时的日志,大部分都是配置的问题,要是C库有问题,及时联系对应库的作者,验证是否为bug!

二丶tolua接入(编写测试Demo)
资源下载:
tolua
https://github.com/topameng/tolua

正文:
1.将lua-protobuf中的protoc.lua、luaunit.lua和serpent.lua拷贝至tolua工程Assets\ToLua\Lua(tolua自带lua)文件夹下或者Assets\Lua(自己的业务lua)下
2.unity打开tolua工程,在LuaDLL.cs public static extern int luaopen_pb(IntPtr L);这行下添加

		// lua-protobuf >>>>>>>
        [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
        public static extern int luaopen_pb_io(IntPtr L);

        [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
        public static extern int luaopen_pb_conv(IntPtr L);

        [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
        public static extern int luaopen_pb_buffer(IntPtr L);

        [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
        public static extern int luaopen_pb_slice(IntPtr L);
        // lua-protobuf <<<<<<

3.在Assets\ToLua\Examples\TestLuaProtobuf新建测试目录,在该目录下新建测试场景TestLuaProtobuf,新建测试脚本TestLuaProtobuf.cs挂于MainCamera下
TestLuaProtobuf.cs脚本如下

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using LuaInterface;
using System;

public class TestLuaProtobuf : MonoBehaviour {
    //lua-protobuf 测试用lua脚本
    string script =
        @"
            local pb = require 'pb'
            local protoc = require 'protoc'

            -- load schema from text
            assert(protoc:load[[
               message Phone {
                    optional string name = 1;
                    optional int64  phonenumber = 2;
                }
                message Person
                {
                    optional string name = 1;
                optional int32  age      = 2;
                  optional string address = 3;
                repeated Phone  contacts = 4;
               } ]])

            -- lua table data
            local data = {
               name = 'ilse',
               age  = 18,
               contacts = {
                  { name = 'alice', phonenumber = 12312341234 },
                  { name = 'bob',   phonenumber = 45645674567 }
               }
            }

            -- encode lua table data into binary format in lua string and return
            local bytes = assert(pb.encode('Person', data))
            print(pb.tohex(bytes))

            -- and decode the binary data back into lua table
            local data2 = assert(pb.decode('Person', bytes))
            print(require 'serpent'.block(data2))
        ";

    int bundleCount = int.MaxValue;
    string tips = null;
    LuaState luaState = null;

    bool testAB = false;//是否打包AB加载

    void Start()
    {
#if UNITY_5 || UNITY_2017 || UNITY_2018
        Application.logMessageReceived += ShowTips;
#else
        Application.RegisterLogCallback(ShowTips);
#endif
        if (!testAB) 
        {
            OnBundleLoad();
            return;
        }
        LuaFileUtils file = new LuaFileUtils();
        file.beZip = true;
#if UNITY_ANDROID && UNITY_EDITOR
        if (IntPtr.Size == 8)
        {
            throw new Exception("can't run this in unity5.x process for 64 bits, switch to pc platform, or run it in android mobile");
        }
#endif
        StartCoroutine(LoadBundles());
    }

    void OnBundleLoad()
    {
        luaState = new LuaState();
        luaState.Start();
        OpenLuaProtobuf();
        luaState.DoString(script);
        luaState.Dispose();
        luaState = null;

    }
    /// 
    /// 这里tolua在OpenLibs的时候并不一定会注册,这里注册一下
    /// 
    void OpenLuaProtobuf()
    {
        luaState.LuaGetField(LuaIndexes.LUA_REGISTRYINDEX, "_LOADED");
        luaState.OpenLibs(LuaDLL.luaopen_pb);
        luaState.LuaSetField(-2, "pb");

        luaState.OpenLibs(LuaDLL.luaopen_pb_io);
        luaState.LuaSetField(-2, "pb.io");

        luaState.OpenLibs(LuaDLL.luaopen_pb_conv);
        luaState.LuaSetField(-2, "pb.conv");

        luaState.OpenLibs(LuaDLL.luaopen_pb_buffer);
        luaState.LuaSetField(-2, "pb.buffer");

        luaState.OpenLibs(LuaDLL.luaopen_pb_slice);
        luaState.LuaSetField(-2, "pb.slice");
    }

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

    void OnGUI()
    {
        GUI.Label(new Rect(Screen.width / 2 - 200, Screen.height / 2 - 150, 400, 300), tips);
    }

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

    IEnumerator CoLoadBundle(string name, string path)
    {
        using (WWW www = new WWW(path))
        {
            if (www == null)
            {
                Debugger.LogError(name + " bundle not exists");
                yield break;
            }

            yield return www;

            if (www.error != null)
            {
                Debugger.LogError(string.Format("Read {0} failed: {1}", path, www.error));
                yield break;
            }

            --bundleCount;
            LuaFileUtils.Instance.AddSearchBundle(name, www.assetBundle);
            www.Dispose();
        }
    }

    IEnumerator LoadFinished()
    {
        while (bundleCount > 0)
        {
            yield return null;
        }

        OnBundleLoad();
    }

    public IEnumerator LoadBundles()
    {
        string streamingPath = Application.streamingAssetsPath.Replace('\\', '/');

#if UNITY_5 || UNITY_2017 || UNITY_2018
#if UNITY_ANDROID && !UNITY_EDITOR
        string main = streamingPath + "/" + LuaConst.osDir + "/" + LuaConst.osDir;
#else
        string main = "file:///" + streamingPath + "/" + LuaConst.osDir + "/" + LuaConst.osDir;
#endif
        WWW www = new WWW(main);
        yield return www;

        AssetBundleManifest manifest = (AssetBundleManifest)www.assetBundle.LoadAsset("AssetBundleManifest");
        List list = new List(manifest.GetAllAssetBundles());
#else
        //此处应该配表获取
        List list = new List() { "lua.unity3d", "lua_cjson.unity3d", "lua_system.unity3d", "lua_unityengine.unity3d", "lua_protobuf.unity3d", "lua_misc.unity3d", "lua_socket.unity3d", "lua_system_reflection.unity3d" };
#endif
        bundleCount = list.Count;

        for (int i = 0; i < list.Count; i++)
        {
            string str = list[i];

#if UNITY_ANDROID && !UNITY_EDITOR
            string path = streamingPath + "/" + LuaConst.osDir + "/" + str;
#else
            string path = "file:///" + streamingPath + "/" + LuaConst.osDir + "/" + str;
#endif
            string name = Path.GetFileNameWithoutExtension(str);
            StartCoroutine(CoLoadBundle(name, path));
        }

        yield return StartCoroutine(LoadFinished());
    }
}

4.各平台测试
pc上
TestLuaProtobuf.cs 脚本中testAB = false,直接运行测试场景TestLuaProtobuf即可,正常输出
tolua集成lua-protobuf库_第2张图片
移动端
TestLuaProtobuf.cs 脚本中testAB = true
unity切换至对应平台,例如切换至Android,执行untiy菜单栏 Lua/Build bundle files no jit,等待打包执行完毕,分别在Assets\StreamingAssets下生成对应平台lua AB包,Android、iOS
tolua集成lua-protobuf库_第3张图片
tolua集成lua-protobuf库_第4张图片
添加测试场景,build 安装包即可!
安卓正常结果
tolua集成lua-protobuf库_第5张图片
问题:
1.关于集成时tolua使用lua-lua-protobuf时的注册问题,两位大佬的issues对答
https://github.com/topameng/tolua/issues/168

你可能感兴趣的:(Lua/Tolua/Xlua)