From b1031c72114862e4588d0cfee6f19719fae240fc Mon Sep 17 00:00:00 2001 From: Mm2PL Date: Wed, 8 Feb 2023 23:57:59 +0100 Subject: [PATCH] Add lua::{peek,push} support for enums with magic_enum --- src/controllers/plugins/LuaUtilities.hpp | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/controllers/plugins/LuaUtilities.hpp b/src/controllers/plugins/LuaUtilities.hpp index eb0a8d661..99f9929b7 100644 --- a/src/controllers/plugins/LuaUtilities.hpp +++ b/src/controllers/plugins/LuaUtilities.hpp @@ -2,10 +2,14 @@ #ifdef CHATTERINO_HAVE_PLUGINS # include "lua.h" +# include "lualib.h" +# include # include # include +# include +# include # include struct lua_State; class QJsonObject; @@ -41,6 +45,25 @@ QString toString(lua_State *L, StackIdx idx = -1); /// TEMPLATES +template , bool>::type = true> +bool peek(lua_State *L, T *out, StackIdx idx = -1) +{ + std::string tmp; + if (!lua::peek(L, &tmp, idx)) + { + return false; + } + std::optional opt = magic_enum::enum_cast(tmp); + if (opt.has_value()) + { + *out = opt.value(); + return true; + } + + return false; +} + template int push(lua_State *L, std::vector vec) { @@ -69,6 +92,13 @@ int push(lua_State *L, QList vec) return out; } +template >> +StackIdx push(lua_State *L, T inp) +{ + std::string_view name = magic_enum::enum_name(inp); + return lua::push(L, std::string(name)); +} + template bool pop(lua_State *L, T *out, StackIdx idx = -1) { @@ -80,5 +110,22 @@ bool pop(lua_State *L, T *out, StackIdx idx = -1) return ok; } +template +StackIdx pushEnumTable(lua_State *L) +{ + // std::array + auto values = magic_enum::enum_values(); + StackIdx out = lua::pushEmptyTable(L, values.size()); + for (const T v : values) + { + std::string_view name = magic_enum::enum_name(v); + std::string str(name); + + lua::push(L, str); + lua_setfield(L, out, str.c_str()); + } + return out; +} + } // namespace chatterino::lua #endif