stack_guard.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // sol2
  2. // The MIT License (MIT)
  3. // Copyright (c) 2013-2022 Rapptz, ThePhD and contributors
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. // this software and associated documentation files (the "Software"), to deal in
  6. // the Software without restriction, including without limitation the rights to
  7. // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  8. // the Software, and to permit persons to whom the Software is furnished to do so,
  9. // subject to the following conditions:
  10. // The above copyright notice and this permission notice shall be included in all
  11. // copies or substantial portions of the Software.
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  14. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  15. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  16. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  18. #ifndef SOL_STACK_GUARD_HPP
  19. #define SOL_STACK_GUARD_HPP
  20. #include <sol/compatibility/lua_version.hpp>
  21. #include <sol/error.hpp>
  22. #include <functional>
  23. namespace sol {
  24. namespace detail {
  25. inline void stack_fail(int, int) {
  26. #if SOL_IS_ON(SOL_EXCEPTIONS)
  27. throw error(detail::direct_error, "imbalanced stack after operation finish");
  28. #else
  29. // Lol, what do you want, an error printout? :3c
  30. // There's no sane default here. The right way would be C-style abort(), and that's not acceptable, so
  31. // hopefully someone will register their own stack_fail thing for the `fx` parameter of stack_guard.
  32. #endif // No Exceptions
  33. }
  34. } // namespace detail
  35. struct stack_guard {
  36. lua_State* L;
  37. int top;
  38. std::function<void(int, int)> on_mismatch;
  39. stack_guard(lua_State* L) : stack_guard(L, lua_gettop(L)) {
  40. }
  41. stack_guard(lua_State* L, int top, std::function<void(int, int)> fx = detail::stack_fail) : L(L), top(top), on_mismatch(std::move(fx)) {
  42. }
  43. bool check_stack(int modification = 0) const {
  44. int bottom = lua_gettop(L) + modification;
  45. if (top == bottom) {
  46. return true;
  47. }
  48. on_mismatch(top, bottom);
  49. return false;
  50. }
  51. ~stack_guard() {
  52. check_stack();
  53. }
  54. };
  55. } // namespace sol
  56. #endif // SOL_STACK_GUARD_HPP