functions.hpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* Luwra
  2. * Minimal-overhead Lua wrapper for C++
  3. *
  4. * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
  5. */
  6. #ifndef LUWRA_FUNCTIONS_H_
  7. #define LUWRA_FUNCTIONS_H_
  8. #include "common.hpp"
  9. #include "types.hpp"
  10. #include "stack.hpp"
  11. LUWRA_NS_BEGIN
  12. /**
  13. * A callable native Lua function.
  14. */
  15. template <typename R>
  16. struct NativeFunction: Reference {
  17. NativeFunction(State* state, int index):
  18. Reference(state, index)
  19. {}
  20. inline
  21. R operator ()() const {
  22. impl->push();
  23. lua_call(impl->state, 0, 1);
  24. R returnValue = Value<R>::read(impl->state, -1);
  25. lua_pop(impl->state, 1);
  26. return returnValue;
  27. }
  28. template <typename... A> inline
  29. R operator ()(A&&... args) const {
  30. impl->push();
  31. size_t numArgs = push(impl->state, std::forward<A>(args)...);
  32. lua_call(impl->state, static_cast<int>(numArgs), 1);
  33. R returnValue = Value<R>::read(impl->state, -1);
  34. lua_pop(impl->state, 1);
  35. return returnValue;
  36. }
  37. };
  38. /**
  39. * A callable native Lua function.
  40. */
  41. template <>
  42. struct NativeFunction<void>: Reference {
  43. NativeFunction(State* state, int index):
  44. Reference(state, index)
  45. {}
  46. inline
  47. void operator ()() const {
  48. impl->push();
  49. lua_call(impl->state, 0, 0);
  50. }
  51. template <typename... A> inline
  52. void operator ()(A&&... args) const {
  53. impl->push();
  54. size_t numArgs = push(impl->state, std::forward<A>(args)...);
  55. lua_call(impl->state, static_cast<int>(numArgs), 0);
  56. }
  57. };
  58. template <typename R>
  59. struct Value<NativeFunction<R>> {
  60. static inline
  61. NativeFunction<R> read(State* state, int index) {
  62. luaL_checktype(state, index, LUA_TFUNCTION);
  63. return {state, index};
  64. }
  65. };
  66. LUWRA_NS_END
  67. #endif