local function default_table(typename)
local v = default_cache[typename]
if v then
return v
end
v = { __index = assert(decode_message(typename , "")) }
default_cache[typename] = v
return v
end
BUG验证
**message Profile** {
optional string nick_name = 1;
optional string icon = 2;
}
message Person {
required string name = 1;
required int32 id = 2; // Unique ID number for this person.
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
repeated int32 test = 5 [packed=true];
**optional Profile profile = 6;**
extensions 10 to max;
}
local addressbook1 = {
name = "Alice",
id = 12345,
phone = {
{ number = "1301234567" },
{ number = "87654321", type = "WORK" },
{ number = "13912345678", type = "MOBILE" },
},
email = "username@domain.com"
}
local addressbook2 = {
name = "Bob",
id = 12346,
phone = {
{ number = "1301234568" },
{ number = "98765432", type = "HOME" },
{ number = "13998765432", type = "MOBILE" },
}
}
code1 = protobuf.encode("tutorial.Person", addressbook1)
code2 = protobuf.encode("tutorial.Person", addressbook2)
decode1 = protobuf.decode("tutorial.Person" , code1)
-- BUG [ISSUE#27](https://github.com/cloudwu/pbc/issues/27)
decode1.profile.nick_name = "AHA"
decode1.profile.icon = "id:1"
decode2 = protobuf.decode("tutorial.Person" , code2)
function print_addr(decoded)
print(string.format('ID: %d, Name: %s, Email: %s', decoded.id, decoded.name, tostring(decoded.email)))
if decoded.profile then
print(string.format('\tNickname: %s, Icon: %s', tostring(decoded.profile.nick_name), tostring(decoded.profile.icon)))
end
for k, v in ipairs(decoded.phone) do
print(string.format("\tPhone NO.%s: %16s %s", k, v.number, tostring(v.type)))
end
end
print_addr(decode1)
print_addr(decode2)
输出的内容如下
$ lua5.1 testparser.lua
ID: 12345, Name: Alice, Email: username@domain.com
Nickname: AHA, Icon: id:1
Phone NO.1: 1301234567 HOME
Phone NO.2: 87654321 WORK
Phone NO.3: 13912345678 MOBILE
ID: 12346, Name: Bob, Email:
Nickname: AHA, Icon: id:1
Phone NO.1: 1301234568 HOME
Phone NO.2: 98765432 HOME
Phone NO.3: 13998765432 MOBILE
local function default_table(typename)
local v = default_cache[typename]
if v then
return v
end
local default_inst = assert(decode_message(typename , ""))
v = {
__index = function(tb, key)
local ret = default_inst[key]
if 'table' ~= type(ret) then
return ret
end
ret = setmetatable({}, { __index = ret })
rawset(tb, key, ret)
return ret
end
}
default_cache[typename] = v
return v
end