Protocol Buffers Lua APIまとめ--内蔵タイプのrepeatedはappend()複合タイプのrepeatedはadd()を使用


本明細書で紹介するprotocol buffersに関するapiは、protoc-gen-lua(see in github)というプロジェクトに基づいている.
私の使用経験はすべてCocosd-xゲームを開発する時、luaスクリプトはサーバーと通信してprotocol bufferを採用して、プロトコルコンパイルツールはprotoc-gen-luaというプラグインです.プラグインのインストールプロセスこのプロジェクトのReadMeはすでにはっきり説明されており、ここでは主に実際の使用で注意しなければならない問題と、生成されたpb.luaの一般的なAPIをコンパイルすることについてまとめます.
基本的な使い方
1.Test.protoというファイルを定義します.
message Test {     required int32 id = 1;     optional string name = 2;     repeated int32 ary = 3;     message Foo {         required int32 fid = 1;         required string fname = 2;     }     repeated Foo foos = 4; }
2.protoc-gen-luaプラグインを使用してprotoをコンパイルし、Test_pb.luaを生成する
protoc --lua_out=./Test.proto
プロジェクトでrequire(「Test_pb」)
--requireが失敗した場合は、luaの`package.path`の使用local pb=require("Test_pb")local test=pb.Test()test.id=1 test.name="hello"test.ary:append(1)--内蔵タイプのrepeated使用append()test.ary:append()test.ary:append(2)local foo 1=pb.foos:add()--複合タイプのrepeated使用add()foo 1.fid=1 foo 1 foo 1 foo 1.fname="foo 1"local foo 2=pb.foos:add()foo 2.fid=2 foo 2.fname="foo 2"--文字列local pb_data=test:SerializeToString()--文字列解析local recover=pb.Test()recover:ParseFromString(pb_data)print(recover.id,recover.foos[1].name,recover.foos[2].na
--requireが失敗した場合は、luaの`package.path`の使用local pb=require("Test_pb")local test=pb.Test()test.id=1 test.name="hello"test.ary:append(1)--内蔵タイプのrepeated使用append()test.ary:append()test.ary:append(2)local foo 1=pb.foos:add()--複合タイプのrepeated使用add()foo 1.fid=1 foo 1 foo 1 foo 1.fname="foo 1"local foo 2=pb.foos:add()foo 2.fid=2 foo 2.fname="foo 2"--文字列local pb_data=test:SerializeToString()--文字列解析local recover=pb.Test()recover:ParseFromString(pb_data)print(recover.id,recover.foos[1].name,recover.foos[2].na