storage.h 945 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* Luwra
  2. * Minimal-overhead Lua wrapper for C++
  3. *
  4. * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
  5. */
  6. #ifndef LUWRA_STORAGE_H_
  7. #define LUWRA_STORAGE_H_
  8. #include "common.h"
  9. LUWRA_NS_BEGIN
  10. /**
  11. * A seperate execution stack, which acts as a storage unit.
  12. */
  13. struct Storage {
  14. State* storage;
  15. /**
  16. * Create the storage unit.
  17. */
  18. inline
  19. Storage(State* parent, int capacity = 0) {
  20. storage = lua_newthread(parent);
  21. lua_pop(parent, 1);
  22. reserve(capacity);
  23. }
  24. /**
  25. * Make sure at least `n` slots are available.
  26. */
  27. inline
  28. void reserve(int n) {
  29. while (lua_gettop(storage) < n) {
  30. lua_pushnil(storage);
  31. }
  32. }
  33. /**
  34. * Fill a slot.
  35. */
  36. template <typename T> inline
  37. void set(int n, T value) {
  38. reserve(n);
  39. lua_remove(storage, n);
  40. Value<T>::push(storage, value);
  41. lua_insert(storage, n);
  42. }
  43. /**
  44. * Implicit conversion to a Lua state.
  45. */
  46. inline
  47. operator State*() {
  48. return storage;
  49. }
  50. };
  51. LUWRA_NS_END
  52. #endif