|
| 1 | +/***************************************************************************** |
| 2 | + * |
| 3 | + * PROJECT: Multi Theft Auto |
| 4 | + * LICENSE: See LICENSE in the top level directory |
| 5 | + * |
| 6 | + * Multi Theft Auto is available from http://www.multitheftauto.com/ |
| 7 | + * |
| 8 | + *****************************************************************************/ |
| 9 | +#pragma once |
| 10 | +#include <stdexcept> |
| 11 | +/* |
| 12 | + * Simple utility to verify the Lua stack. |
| 13 | + * The general idea is to simply write |
| 14 | + * LUA_STACK_EXPECT(N); |
| 15 | + * at the beginning of a function, where N |
| 16 | + * is the expected amount of change in the Lua |
| 17 | + * stack size. |
| 18 | + * |
| 19 | + * As an example: A __index metamethod receives |
| 20 | + * two parameters on the stack and returns a |
| 21 | + * single value. Therefor each __index |
| 22 | + * implementation should decrease the Lua stack |
| 23 | + * size by one. Therefore write: |
| 24 | + * LUA_STACK_EXPECT(-1); |
| 25 | + */ |
| 26 | +namespace lua |
| 27 | +{ |
| 28 | + struct CLuaStackChecker |
| 29 | + { |
| 30 | + lua_State* L; |
| 31 | + int m_iTop = 0; |
| 32 | + int m_iExpected = 0; |
| 33 | + CLuaStackChecker(lua_State* L, int expected) : L(L) |
| 34 | + { |
| 35 | + m_iTop = lua_gettop(L); |
| 36 | + m_iExpected = expected; |
| 37 | + } |
| 38 | + |
| 39 | + ~CLuaStackChecker() noexcept(false) |
| 40 | + { |
| 41 | + int iNewtop = lua_gettop(L); |
| 42 | + int iChange = iNewtop - m_iTop; |
| 43 | + if (iChange != m_iExpected) |
| 44 | + { |
| 45 | + printf("Lua Stack Error: top should be %d is %d (change should be %d is %d)\n", m_iTop + m_iExpected, iNewtop, m_iExpected, iChange); |
| 46 | + throw std::runtime_error("Lua Stack Error"); |
| 47 | + } |
| 48 | + } |
| 49 | + }; |
| 50 | +} // namespace lua |
| 51 | + |
| 52 | +#ifdef MTA_DEBUG |
| 53 | +#define LUA_STACK_EXPECT(i) lua::CLuaStackChecker invalidHiddenName(L, i) |
| 54 | +#else |
| 55 | +#define LUA_STACK_EXPECT(i) |
| 56 | +#endif |
0 commit comments