Rotating Header Image

Lua Serializer

By request, I put the serializer I wrote in lua on my wiki.

It is a serializer I once wrote for a mud I was working on in lua. In the end I got the framework finished but never the game-code. The nice thing of this serializer is that it is possible to define custom serialization functions. I used this with a class-based OO system where I would serialize classes by name, not by value. That way if I reload the code and then serialize and deserialize my data, I would have the new method-bindings in my objects.

The usage is rather simple:

local f ="somefilename", "w")
local s =
s:serialize(mydata, "mydata")s:flush()f:close()

It is possible to define custom serialization by defining the __serialize function in the metatable. The function should be named __serialize and take three parameters:

  • value – the value that it is serializing
  • serializer – the serializer to use to write to the file (through serializer:write(…))
  • name – the name of the variable

For example, the following will ensure that the table ‘t’ is always outputted as an empty table. It is important the name is used, as this can be a rather long name (for instance, a field of a field of a table..)

local mt = {}
local t = setmetatable({}, mt)
mt.__serialize = function(value, serializer, name)
  serializer:write(name, " = ", "{}", "\n")
Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>