state.hpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /* Luwra
  2. * Minimal-overhead Lua wrapper for C++
  3. *
  4. * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
  5. */
  6. #ifndef LUWRA_STATEWRAPPER_H_
  7. #define LUWRA_STATEWRAPPER_H_
  8. #include "common.hpp"
  9. #include "auxiliary.hpp"
  10. #include "tables.hpp"
  11. #include <string>
  12. #include <utility>
  13. LUWRA_NS_BEGIN
  14. /**
  15. * Wrapper for a Lua state
  16. */
  17. struct StateWrapper: Table {
  18. State* state;
  19. bool close_state;
  20. /**
  21. * Operate on a foreign state instance.
  22. */
  23. inline
  24. StateWrapper(State* state):
  25. Table(getGlobalsTable(state)),
  26. state(state),
  27. close_state(false)
  28. {}
  29. /**
  30. * Create a new Lua state.
  31. */
  32. inline
  33. StateWrapper():
  34. Table(getGlobalsTable(luaL_newstate())),
  35. state(ref.impl->state),
  36. close_state(true)
  37. {}
  38. inline
  39. ~StateWrapper() {
  40. if (close_state)
  41. lua_close(state);
  42. }
  43. inline
  44. operator State*() {
  45. return state;
  46. }
  47. inline
  48. void loadStandardLibrary() {
  49. luaL_openlibs(state);
  50. }
  51. /**
  52. * See [luwra::registerUserType](@ref luwra::registerUserType).
  53. */
  54. template <typename T> inline
  55. void registerUserType(
  56. const std::string& ctor_name,
  57. const FieldVector& methods = FieldVector(),
  58. const FieldVector& meta_methods = FieldVector()
  59. ) {
  60. ::luwra::registerUserType<T>(state, ctor_name, methods, meta_methods);
  61. }
  62. /**
  63. * Execute a piece of code.
  64. */
  65. inline
  66. int runString(const std::string& code) {
  67. return luaL_dostring(state, code.c_str());
  68. }
  69. /**
  70. * Execute a file.
  71. */
  72. inline
  73. int runFile(const std::string& filepath) {
  74. return luaL_dofile(state, filepath.c_str());
  75. }
  76. };
  77. LUWRA_NS_END
  78. #endif