Serializing functions
20260105T222734
When you write software for yourself, you'll want to serialize objects to disk, say, flashcards. But what if I want to imbue one particular flashcard with its own functionality? You could coin a label for such behavior, hardcode the behavior into the interpreting program, then serialize the key; that seems silly to do for every card with custom behavior. Plus,it makes rewriting or porting the interpreter very cumbersome. It would be better in this case to be able to serialize the function directly.
Unfortunately (in this particular case), most programming languages compile or otherwise transform functions immediately upon definition, rendering them either not human-readable or not deserializable at all.
This note collects tricks and tools that make this possible.
In Lua
One possible trick: write the function in a string from the get-go, then =load= it before use. Then it can be trivially serialized as a string. Example:
-- block returning anon. fn.
double_fstr = "return function (x) return x + x end"
serialize(file)
double_fstr_resurrected = deserialize(file)
assert(type(double_fstr_resurrected) == 'string')
-- load wraps in an extra fn.
double_fn = load(double_fstr_resurrected)
-- finally, the function itself
double = double_fn()
assert(double(5) == 10)
Each of some persistent object keeps a =fstr= and a =fn= field. =fn= is ignored when serializing but is populating using =fstr=, as above, just after deserializing.