Reputation: 113
I need to send a lua_state to a server using Sockets in C ++. How I can serialize a lua_State so that it can be sent over the network?
Upvotes: 4
Views: 2227
Reputation: 16753
Depending on your needs, you have several choices. You can try to use the Pluto Library. It is a "heavy-weight" serialization library:
Pluto is a library which allows users to write arbitrarily large portions of the "Lua universe" into a flat file, and later read them back into the same or a different Lua universe. Object references are appropriately handled, such that the file contains everything needed to recreate the objects in question.
You may also try lper, which uses Linux Persistent Memory.
Note that you will have problems with sending custom C functions and userdata...
If you actually do not need to send entire lua_State
(why would you need that?), you can take a look at the TableSerialization page at the Lua-users Wiki. Maybe you can solve your problem by sending serialized (possibly large) Lua tables containing the entire "state" you need.
Upvotes: 4
Reputation: 889
Well, I don't know how you would pass the actual lua_state over a socket. Perhaps you can extract the information contained in the lua_state and then pass the extracted information over the socket?
std::string name(lua_tostring(L,1));
int age = lua_tonumber(L,2);
//then send name and string over the socket somehow...
And if you have any response from the socket that you would like to forward to lua just do something like
//get response from socket and push response to lua
lua_pushnumber(L, response);
return 1; //indicate how arguments you are returning.
Hope it helps. Good luck!
Upvotes: 0
Reputation: 473537
Serializing a full lua_State
is fundamentally impossible. After all, even if you could transmit the memory stored in one, lua_State
s have many C functions attached to them. How could you serialize one of those across the network?
The best you can hope for is to try to remember what you did in one Lua state and tell the program across the network to do the same. This will require writing an abstraction of Lua's interface, which you call instead of Lua's interface. It will report every action you take to the networked program. File loading would also have to transmit that file to the networked program.
Basically, you have to take every Lua function and write a new version of it that calls the old one and tells the networked program what you're doing.
Upvotes: 4