diff --git a/Source/debug.cpp b/Source/debug.cpp index cd37f188a..cbbb3cd10 100644 --- a/Source/debug.cpp +++ b/Source/debug.cpp @@ -35,6 +35,7 @@ #include "utils/file_util.h" #include "utils/language.h" #include "utils/log.hpp" +#include "utils/lua.hpp" #include "utils/parse_int.hpp" #include "utils/str_case.hpp" #include "utils/str_cat.hpp" @@ -152,6 +153,15 @@ std::string DebugCmdHelp(const std::string_view parameter) return StrCat("Description: ", dbgCmdItem.description, "\nParameters: ", dbgCmdItem.requiredParameter); } +std::string DebugCmdLua(std::string_view code) +{ + tl::expected result = RunLua(code); + if (!result.has_value()) { + return StrCat("> ", code, "\n") + std::move(result).error(); + } + return StrCat("> ", code, "\n") + std::move(result).value(); +} + std::string DebugCmdGiveGoldCheat(const std::string_view parameter) { Player &myPlayer = *MyPlayer; @@ -1231,6 +1241,7 @@ std::vector DebugCmdList = { { "searchitem", "Searches the automap for {item}", "{item}", &DebugCmdSearchItem }, { "searchobject", "Searches the automap for {object}", "{object}", &DebugCmdSearchObject }, { "clearsearch", "Search in the auto map is cleared", "", &DebugCmdClearSearch }, + { "lua", "Run Lua code", "{code}", &DebugCmdLua }, }; } // namespace diff --git a/Source/utils/lua.cpp b/Source/utils/lua.cpp index 16d22926b..043fca442 100644 --- a/Source/utils/lua.cpp +++ b/Source/utils/lua.cpp @@ -4,6 +4,7 @@ #include #include +#include #include "engine/assets.hpp" #include "engine/dx.h" @@ -137,4 +138,19 @@ void LuaEvent(std::string_view name) CheckResult(fn()); } +tl::expected RunLua(std::string_view code) +{ + sol::state &lua = *luaState; + const sol::protected_function_result result = lua.safe_script(code); + const bool valid = result.valid(); + if (!valid) { + if (result.get_type() == sol::type::string) { + return tl::make_unexpected(result.get()); + } + return tl::make_unexpected("Unknown Lua error"); + } + + return sol::utility::to_string(sol::object(result)); +} + } // namespace devilution diff --git a/Source/utils/lua.hpp b/Source/utils/lua.hpp index 141271d2f..2bb3785ac 100644 --- a/Source/utils/lua.hpp +++ b/Source/utils/lua.hpp @@ -2,10 +2,13 @@ #include +#include + namespace devilution { void LuaInitialize(); void LuaShutdown(); void LuaEvent(std::string_view name); +tl::expected RunLua(std::string_view code); } // namespace devilution