ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.06k stars 492 forks source link

Saving C++ structures as Lua files #1525

Closed pozemka closed 7 months ago

pozemka commented 9 months ago

Hello! I am loading Lua table to C++ structure and want to do the opposite — save it to .lua file. For example, my lua file is

return {
  name = "lvl1",
  width = 31
}

In C++ I am doing this:

struct Level{
  std::string name;
  int width {};
};
sol::state lua;
lua.open_libraries(sol::lib::base);
sol::table lvl_data = lua.script_file("my_level.lua");
Level level {
  .name = lvl_data["name"],
  .width = lvl_data["width"],
};

I there a simple way to save my Level structure as Lua code. Perhaps with some limitations but without writing Lua codegen?

Something like this:

sol::table lvl_data;
lvl_data["name"] = "Hello";
lvl_data["width"] = 123;
std::string lua_code = lvl_data.dump_lua();

Or this is out of sol2 scope?

deadlocklogic commented 7 months ago

This could be addressed with many solutions (all of them require some kind of extra effort), here are 2 approaches: 1- Serialization/Deserialization: You could write a serialization/deserialization factory which handle how C++ structs are read from Lua table, written to Lua table. This will be the cleanest by far. 2- Use a runtime reflection library to register your needed C++ types and then use the reflection data to serialize/deserialize C++/Lua.

So basically yes, it is out of sol2 scope.