3 Copyright (C) 2020 Elias Fleckenstein <eliasfleckenstein@web.de>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "cpp_api/s_cheats.h"
21 #include "cpp_api/s_base.h"
22 #include "cpp_api/s_internal.h"
25 ScriptApiCheatsCheat::ScriptApiCheatsCheat(const std::string &name, const std::string &setting) :
33 ScriptApiCheatsCheat::ScriptApiCheatsCheat(const std::string &name, const int &function) :
36 m_function_ref(function)
40 bool ScriptApiCheatsCheat::is_enabled()
42 return ! m_function_ref && g_settings->getBool(m_setting);
45 void ScriptApiCheatsCheat::toggle(lua_State *L, int error_handler)
48 lua_rawgeti(L, LUA_REGISTRYINDEX, m_function_ref);
49 lua_pcall(L, 0, 0, error_handler);
51 g_settings->setBool(m_setting, !g_settings->getBool(m_setting));
54 ScriptApiCheatsCategory::ScriptApiCheatsCategory(const std::string &name) :
59 ScriptApiCheatsCategory::~ScriptApiCheatsCategory()
61 for (auto i = m_cheats.begin(); i != m_cheats.end(); i++)
65 void ScriptApiCheatsCategory::read_cheats(lua_State *L)
68 while (lua_next(L, -2)) {
69 ScriptApiCheatsCheat *cheat = nullptr;
70 std::string name = lua_tostring(L, -2);
71 if (lua_isstring(L, -1))
72 cheat = new ScriptApiCheatsCheat(name, lua_tostring(L, -1));
73 else if (lua_isfunction(L, -1)) {
74 cheat = new ScriptApiCheatsCheat(name, luaL_ref(L, LUA_REGISTRYINDEX));
78 m_cheats.push_back(cheat);
83 ScriptApiCheats::~ScriptApiCheats()
85 for (auto i = m_cheat_categories.begin(); i != m_cheat_categories.end(); i++)
89 void ScriptApiCheats::init_cheats()
91 SCRIPTAPI_PRECHECKHEADER
93 lua_getglobal(L, "core");
94 lua_getfield(L, -1, "cheats");
95 if (! lua_istable(L, -1)) {
100 while (lua_next(L, -2)) {
101 if (lua_istable(L, -1)) {
102 ScriptApiCheatsCategory *category = new ScriptApiCheatsCategory(lua_tostring(L, -2));
103 category->read_cheats(L);
104 m_cheat_categories.push_back(category);
109 m_cheats_loaded = true;
112 void ScriptApiCheats::toggle_cheat(ScriptApiCheatsCheat *cheat)
114 SCRIPTAPI_PRECHECKHEADER
116 PUSH_ERROR_HANDLER(L);
117 int error_handler = lua_gettop(L) - 1;
118 lua_insert(L, error_handler);
120 cheat->toggle(L, error_handler);