PrevUpHomeNext

API Persistent Value

api::persistent_value is an easy way that you can create a C++ object, not part of the global table nor of the registry, which gets serialized and restored along with the lua VM.

The value must have a type which is both readable and pushable, and is nothrow_move_constructible.

The class template persistent_value<T> contains the value and implements the API Feature methods.

The contained value can be accessed using get() method, or directly as .value public member.

Synopsis
namespace primer {
namespace api {

template <typename T>
struct persistent_value {
  T value_;

  T & get() & { return value_; }
  T const & get() const & { return value_; }

  //
  // API Feature
  //

  void on_init(lua_State *) {}
  void on_persist_table(lua_State *) {}
  void on_unpersist_table(lua_State *) {}

  void on_serialize(lua_State * L) { primer::push(L, value_); }

  PRIMER_STATIC_ASSERT(std::is_nothrow_move_constructible<T>::value,
                       "persistent value must be nothrow move constructible");
  void on_deserialize(lua_State * L) {
    if (auto result = primer::read<T>(L, -1)) {
      value_ = std::move(*result);
    } else {
      // XXX TODO
    }
    lua_pop(L, 1);
  }
};

} // end namespace api
} // end namespace primer

PrevUpHomeNext