[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: How to exchange the values of a specific variable (e.g: maybe a table) between Lua_States?
- From: Paul Ducklin <pducklin@...>
- Date: Sun, 25 Apr 2021 18:39:05 +0000
>How to exchange the values of a specific
variable (e.g: maybe a table) between Lua_States?
Encode table in state A -> Pass JSON as a string message to state B -> Decode table in state B.
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.
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.
If you want to change the table in state B and have those changes reflected in state A, you send the updated table back as a JSON string.
(Basically, everything you copy needs to be copied by value, not by name or reference, thus avoiding the need for mutexes, semaphores and other thread safety troubles.)