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:

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.

Proxied content from gemini://tykozic.net/gmi/20260105T222734--serializing-functions.gmi

Gemini request details:

Original URL
gemini://tykozic.net/gmi/20260105T222734--serializing-functions.gmi
Status code
Success
Meta
text/gemini;lang=en
Proxied by
kineto

Be advised that no attempt was made to verify the remote SSL certificate.