fields.hpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* Luwra
  2. * Minimal-overhead Lua wrapper for C++
  3. *
  4. * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
  5. */
  6. #ifndef LUWRA_FIELDS_H_
  7. #define LUWRA_FIELDS_H_
  8. #include "common.hpp"
  9. #include "types.hpp"
  10. LUWRA_NS_BEGIN
  11. namespace internal {
  12. /**
  13. * Helper struct for wrapping user type fields
  14. */
  15. template <typename T>
  16. struct FieldWrapper {
  17. static_assert(
  18. sizeof(T) == -1,
  19. "Parameter to FieldWrapper is not a property signature"
  20. );
  21. };
  22. template <typename T, typename R>
  23. struct FieldWrapper<R T::*> {
  24. template <R T::* field_pointer> static inline
  25. int invoke(State* state) {
  26. if (lua_gettop(state) > 1) {
  27. read<T*>(state, 1)->*field_pointer = read<R>(state, 2);
  28. return 0;
  29. } else {
  30. return push(state, read<T*>(state, 1)->*field_pointer);
  31. }
  32. }
  33. };
  34. template <typename T, typename R>
  35. struct FieldWrapper<const R T::*> {
  36. template <const R T::* field_pointer> static inline
  37. int invoke(State* state) {
  38. return push(state, read<T*>(state, 1)->*field_pointer);
  39. }
  40. };
  41. }
  42. LUWRA_NS_END
  43. /**
  44. * Generate a `lua_CFunction` get/set wrapper for a property accessor.
  45. * \param field Fully qualified property name (Do not supply a pointer)
  46. * \return Wrapped function as `lua_CFunction`
  47. */
  48. #define LUWRA_WRAP_FIELD(field) \
  49. (&luwra::internal::FieldWrapper<decltype(&field)>::invoke<&field>)
  50. #endif