Add lua::{peek,push} support for enums with magic_enum

This commit is contained in:
Mm2PL 2023-02-08 23:57:59 +01:00
parent da05115506
commit b1031c7211
No known key found for this signature in database
GPG key ID: 94AC9B80EFA15ED9

View file

@ -2,10 +2,14 @@
#ifdef CHATTERINO_HAVE_PLUGINS
# include "lua.h"
# include "lualib.h"
# include <magic_enum.hpp>
# include <QList>
# include <string>
# include <string_view>
# include <type_traits>
# include <vector>
struct lua_State;
class QJsonObject;
@ -41,6 +45,25 @@ QString toString(lua_State *L, StackIdx idx = -1);
/// TEMPLATES
template <typename T,
typename std::enable_if<std::is_enum_v<T>, 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<T> opt = magic_enum::enum_cast<T>(tmp);
if (opt.has_value())
{
*out = opt.value();
return true;
}
return false;
}
template <typename T>
int push(lua_State *L, std::vector<T> vec)
{
@ -69,6 +92,13 @@ int push(lua_State *L, QList<T> vec)
return out;
}
template <typename T, std::enable_if<std::is_enum_v<T>>>
StackIdx push(lua_State *L, T inp)
{
std::string_view name = magic_enum::enum_name<T>(inp);
return lua::push(L, std::string(name));
}
template <typename T>
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 <typename T>
StackIdx pushEnumTable(lua_State *L)
{
// std::array<T, _>
auto values = magic_enum::enum_values<T>();
StackIdx out = lua::pushEmptyTable(L, values.size());
for (const T v : values)
{
std::string_view name = magic_enum::enum_name<T>(v);
std::string str(name);
lua::push(L, str);
lua_setfield(L, out, str.c_str());
}
return out;
}
} // namespace chatterino::lua
#endif