[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Fun with serializing Lua functions (was Re: Sharing userdata among stats.)
- From: Sean Conner <sean@...>
- Date: Fri, 30 Jun 2017 22:48:50 -0400
It was thus said that the Great Sean Conner once stated:
>
> Functions are an interesting problem. Yes, you can get the bytecode
> (string.dump()) but there are issues: 1) the default serialization of
> functions will only work on the same architecture and 2) does not contain
> the current values of any upvalues. 1) is not an issue with your usecase,
> but 2) is. Again, that can be worked around by not only encoding the
> function (via string.dump()) but also including any upvalues, which can get
> quite interesting (oh, an upvalue might be math.floor() or _G itself!).
So I played around with this today, and I created a github repository for
those interested:
https://github.com/spc476/LuaFunctionSerialize
Right now, the code only supports Lua 5.1, and is not meant for any real
production (it's just a "proof-of-concept" right now). But it works. At
least, for the one complicated recursive function I've tested so far.
1) It uses string.dump() to get the bytecode
2) It serializes any upvalues [1]
3) It only serializes the environment if it's the global environment
4) It can handle any normal Lua global value (like io.stdin or getmetatable)
5) It will probably fail horribly if given a Lua function written in
C (I did not check for this condition)
So there you have it. Something to play around with.
-spc
[1] bools, numbers, tables and functions. Tables can have cycles.