Skip to content

Commit 0ce4777

Browse files
committed
Added CLuaStackChecker
1 parent 384c1b6 commit 0ce4777

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

Shared/mods/deathmatch/logic/lua/CLuaFunctionParser.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include <variant>
1313
#include <SharedUtil.Template.h>
1414
#include "lua/CLuaFunctionParseHelpers.h"
15+
#include "lua/CLuaStackChecker.h"
1516
#include "lua/LuaBasic.h"
1617

1718
template <bool, auto*>
@@ -246,6 +247,8 @@ struct CLuaFunctionParser<ErrorOnFailure, Func>
246247
template <typename T>
247248
inline T PopUnsafe(lua_State* L, std::size_t& index)
248249
{
250+
// Expect no change in stack size
251+
LUA_STACK_EXPECT(0);
249252
// trivial types are directly popped
250253
if constexpr (std::is_same_v<T, std::string> || std::is_same_v<T, int> || std::is_same_v<T, float> || std::is_same_v<T, double> ||
251254
std::is_same_v<T, short> || std::is_same_v<T, unsigned int> || std::is_same_v<T, unsigned short> || std::is_same_v<T, bool>)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)