[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to exchange the values of a specific variable (e.g: maybe a table) between Lua_States?
- From: Sean Conner <sean@...>
- Date: Sun, 25 Apr 2021 17:19:18 -0400
It was thus said that the Great Paul Ducklin once stated:
> >How to exchange the values of a specific
> variable (e.g: maybe a table) between Lua_States?
>
> Try dkjson.
>
> Encode table in state A -> Pass JSON as a string message to state B ->
> Decode table in state B.
>
> Easy.
>
> Obviously you can’t pass userdata keys or values in the table you send
> across (userdata variables are typically full of pointers, malloc()ed
> buffers and system handles, etc. ). You can only copy over only strings
> and numbers.
Or try CBOR [1]. My implementation [2][3] can handle keys other than
strings or integers, and can even handle cycles in tables. Encoding this
table:
local x
x =
{
[1] = true,
[false] = "nah",
[true] = "one",
[42] = "meaning of life",
[math.pi] = 3.000000,
[math.huge] = 'too large',
[math.maxinteger] = 'this is fine',
['NaN'] = 0/0,
[0] = false,
}
is no issue. [5]
> If you want to pass open LuaSockets, however, there is a neat trick where
> you extract the fd from the socket in state A using the socket:getfd()
> method, pass it as a number (it is just a numeric file handle), graft it
> into an unconnected socket in state B using socket:setfd(), and then
> invalidate the fd in the original socket in state A so the fd doesn’t get
> close()d when the “donor” socket gets garbage-collected.
That works as long as the the two Lua states are in the same process.
Back in 2017 I did some playing around with serializing Lua functions [4].
I didn't finalize anything, but I did come up with some interesting
solutions to some of the issues. CBOR also allows values to be semantically
tagged. Using this, I would encode known Lua values, like io.stdin, as a
string, but tagged as a "Lua global". Such semantic tagging could also be
used for other userdata, functions, etc.
-spc
[1] Concise Binary Object Representation
[2] https://github.com/spc476/CBOR
[3] Also available via Luarocks as "org.conman.cbor".
[4] https://github.com/spc476/LuaFunctionSerialize
[5] Try that with JSON!