Google protobuf support for Lua
English | 中文
This project offers a C module for Lua (5.1, 5.2, 5.3, 5.4, 5.5 and LuaJIT) manipulating Google's protobuf protocol, both for version 2 and 3 syntax and semantics. It splits to the lower-level and the high-level parts for different goals.
For converting between binary protobuf data with Lua tables, using pb.load() loads the compiled protobuf schema content (*.pb file) generated by Google protobuf's compiler named protoc and call pb.encode()/pb.decode().
Or use these modules to manipulate the raw wire format in lower-level way:
pb.slice: a wire format decoding module.
pb.buffer: a buffer implement that use to encode basic types into protobuf's wire format. It can be used to support streaming decode protobuf data.
pb.conv: a module converting integers in the protobuf wire format.
pb.io: a module access stdin/stdout or other files in binary mode.
If you don't want to depend Google's protobuf compiler, protoc.lua is a pure Lua module translating text-based protobuf schema content into the *.pb binary format.
Install
To install, you could just use luarocks:
luarocks install lua-protobuf
If you want to build it from source, just clone the repo and use luarocks:
git clone https://github.com/starwing/lua-protobuf
luarocks make rockspecs/lua-protobuf-scm-1.rockspec
If you don't have luarocks, use hererocks to install Lua and luarocks:
pip install hererocks
git clone https://github.com/starwing/lua-protobuf
hererocks -j 2.0 -rlatest .
bin/luarocks make lua-protobuf/rockspecs/lua-protobuf-scm-1.rockspec CFLAGS="-fPIC -Wall -Wextra" LIBFLAGS="-shared"
cp protoc.lua pb.so ..
Or you can build it by hand, it only has a pure Lua module protoc.lua and a pair of C source: pb.h and pb.c. Notice that in order to build the pb C module, you need Lua header file and/or libary file installed. replace $LUA_HEADERS and $LUA_LIBS below to real install locations.
To build it on macOS, use your favor compiler:
gcc -O2 -shared -undefined dynamic_lookup -I "$LUA_HEADERS" pb.c -o pb.so
On Linux, use the nearly same command:
gcc -O2 -shared -fPIC -I "$LUA_HEADERS" pb.c -o pb.so
On Windows, you could use MinGW or MSVC, create a *.sln project or build it on the command line (notice the Lua_BUILD_AS_DLL flag):
cl /O2 /LD /Fepb.dll /I "$LUA_HEADERS" /DLUA_BUILD_AS_DLL pb.c "$LUA_LIBS"
Or use the bundled build.bat to build a release pb.dll with MSVC (static CRT, no VC runtime dependency):
build.bat 5.5 msvc
The first argument selects 5.4, 5.5 or jit; LUA_INC and LUA_LIB override the default Lua paths.
Example
local pb = require "pb"
local protoc = require "protoc"
-- load schema from text (just for demo, use protoc.new() in real world)
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))
Use case

Usage
protoc Module
| Function |
Returns |
Descriptions |
protoc.new() |
Proroc object |
create a new compiler instance |
protoc.reload() |
true |
reload all google standard messages into pb module |
p:parse(string) |
table |
transform schema to DescriptorProto table |
p:compile(string) |
string |
transform schema to binary *.pb format data |
p:load(string) |
true |
load schema into pb module |
p.loaded |
table |
contains all parsed DescriptorProto table |
p.unknown_import |
see below |
handle schema import error |
p.unknown_type |
see below |
handle unknown type in schema |
p.include_imports |
bool |
auto load imported proto |
p.proto3_optional |
bool |
allow proto3 optional fields (default true) |
To parse a text schema content, create a compiler instance first:
local p = protoc.new()
Then, set some options to the compiler, e.g. the unknown handlers:
-- set some hooks
p.unknown_import = function(self, module_name) ... end
p.unknown_type = function(self, type_name) ... end
-- ... and options
p.include_imports = true
The unknown_import and unknown_type handle could be true, string or a function. Seting it to true means all non-exist modules and types are given a default value without triggering an error; A string means a Lua pattern that indicates whether an unknown module or type should raise an error, e.g.
p.unknown_type = "Foo.*"
means all types prefixed by Foo will be treat as existing type and do not trigger errors.
If these are functions, the unknown type and module name will be passed to functions. For module handler, it should return a DescriptorProto Table produced by p:load() functions, for type handler, it should return a type name and type, such as message or enum, e.g.
function p:unknown_import(name)
-- if can not find "foo.proto", load "my_foo.proto" instead
return p:parsefile("my_"..name)
end
function p:unknown_type(name)
-- if cannot find "Type", treat it as ".MyType" and is a message type return ".My"..name, "message"
end
proto3 optional fields are accepted by default, like protoc 3.15+. Set
p.proto3_optional = false to reject them again (proto3 disallow 'optional' label). optional is also accepted on extension fields (proto3 only allows
extending the google.protobuf.*Options messages).
After setting options, use load() or compile() or parse() function to get result.
pb Module
pb module has high-level routines to manipulate protobuf messages.
In below table of functions, we have several types that have special means:
type: a string that indicates the protobuf message type, ".Foo" means the type in a proto definition that has not package statement declared. "foo.Foo" means the type in a proto definition that declared package foo;
data: could be string, pb.Slice value or pb.Buffer value.
iterator: a function that can use in Lua for in statement, e.g.
for name in pb.types() do
print(name)
end
NOTICE: Only pb.load() returns error on failure, do check the result it returns. Other routines raise a error when failure for convenience.
Malformed messages are rejected: pb.decode() and pb.unpack() raise an error instead of silently returning a partial table when an unknown field cannot be skipped (for example, invalid unknown field 15 at offset 2).
Encoding and decoding also cap the message nesting depth and raise message too complex when it is exceeded.
| Function |
Returns |
Description |
pb.clear() |
None |
clear all types |
pb.clear(type) |
None |
delete specific type |
pb.load(data) |
boolean,integer |
load a binary schema data into pb module |
pb.encode(type, table) |
string |
encode a message table into binary form |
pb.encode(type, table, b) |
buffer |
encode a message table into binary form to buffer |
pb.decode(type, data) |
table |
decode a binary message into Lua table |
pb.decode(type, data, table) |
table |
decode a binary message into a given Lua table |
pb.pack(type, ...) |
string |
encode a message with flatten fields (ordered by field number) |
pb.unpack(data, type, ...) |
values... |
decode a message with flatten fields (just like above) |
pb.types() |
iterator |
iterate all types in pb module |
pb.type(type) |
see below |
return informations for specific type |
pb.fields(type) |
iterator |
iterate all fields in a message |
pb.field(type, string) |
see below |
return informations for specific field of type |
pb.typefmt(type) |
string |
transform type name of field into pack/unpack formatter |
pb.enum(type, string) |
number |
get the value of a enum by name |
pb.enum(type, number) |
string |
get the name of a enum by value |
pb.defaults(type[, table/nil]) |
table |
get the default table of type |
pb.hook(type[, function]) |
function |
get or set hook functions |
pb.encode_hook(type[, function]) |
function |
get or set encode hook functions |
pb.option(string) |
string |
set options to decoder/encoder |
pb.state() |
pb.State |
retrieve current pb state |
pb.state(newstate | nil) |
pb.State |
set new pb state and retrieve the old one |
pb.tohex(string) |
string |
encode string as hexadigits, for debug purposes |
Schema loading
pb.load() accepts the schema binary data and returns a boolean indicates the result of loading, success or failure, and a offset reading in schema so far that is useful to figure out the reason of failure.
Type mapping
| Protobuf Types |
Lua Types |
double, float |
number |
int32, uint32, fixed32, sfixed32, sint32 |
number or integer in Lua 5.3+ |
int64, uint64, fixed64, sfixed64, sint64 |
number or "#" prefixed string or integer in Lua 5.3+ |
bool |
boolean |
string, bytes |
string |
message |
table |
enum |
string or number |
Type Information
Using pb.(type|field)[s]() functions retrieve type information for loaded messages.
pb.type() returns multiple informations for specified type:
- name : the full qualifier name of type, e.g. ".package.TypeName"
- basename: the type name without package prefix, e.g. "TypeName"
"map" | "enum" | "message": whether the type is a map_entry type, enum type or message type.
pb.types() returns a iterators, behavior like call pb.type() on every types of all messages.
print(pb.type "MyType")
-- list all types that loaded into pb
for name, basename, type in pb.types() do
print(name, basename, type)
end
pb.field() returns information of the specified field for one type:
- name: the name of the field
- number: number of field in the schema
- type: field type
- default value: if no default value, nil
"packed"|"repeated"| "optional": label of the field, optional or repeated, required is not supported
- [oneof_name, oneof_index]: if this is a
oneof field, this is the oneof name and index
And pb.fields() iterates all fields in a message:
print(pb.field("MyType", "the_first_field"))
-- notice that you needn't receive all return values from iterator
for name, number, type in pb.fields "MyType" do
print(name, number, type)
end
pb.enum() maps from enum name and value:
protoc:load [[
enum Color { Red = 1; Green = 2; Blue = 3 }
]]
print(pb.enum("Color", "Red")) --> 1
print(pb.enum("Color", 2)) --> "Green"
Default Values
Using pb.defaults() to get or set a table with all default values from a message. this table will be used as the metatable of the corresponding decoded message table when setting use_default_metatable option.
You could also call pb.defaults with "*map" or "*array" to get the default metatable for map and array when decoding a message. These settings will bypass use_default_metatable option.
To clear a default metatable, just pass nil as second argument to pb.defaults().