有没有一种好的方式使用Luabridge将sf::Event暴露给Lua?

根据LuaBridge自述,LuaBridge不支持“枚举常量”,我想这就是enums。由于sf :: Event几乎完全是enums,有没有办法我可以公开这个类?目前我能想到的唯一其他解决方案是在C ++中检测按键,然后将描述事件的字符串发送到Lua。显然,现代键盘上有100多个键,这会导致一个庞大而丑陋的段落,只有条件语句。

对于那些没有使用SFML的人:链接到sf :: Event类源代码


更新:

在尝试创建我在问题中概述的函数后,我发现它根本不起作用,因为您无法返回多个字符串,因此大多数事件都被忽略。

示例源代码(不起作用):

std :: string getEvent()
{
    sf :: Event event;
    while(window.pollEvent(event))
    {
        if(event.type == sf :: Event :: Closed){window.close();返回“”;}
        else if(event.type == sf :: Event :: GainedFocus){return“GainedFocus”;}
        else if(event.type == sf :: Event :: LostFocus){return“LostFocus”;}
        else if(event.type == sf :: Event :: Resized){return“Resized”;}
        else if(event.type == sf :: Event :: TextEntered)
        {
            如果((event.text.unicode <128)&&(event.text.unicode> 0)){return“”+ static_cast <char>(event.text.unicode); }
        }
        else if(event.type == sf :: Event :: KeyPressed)
        {
            //如果键盘上的所有键
        }
        else if(event.type == sf :: Event :: KeyReleased)
        {
            //如果键盘上的所有键
        }
        else {返回“”;}
    }
    返回“”;
}

更新更新:

由于这个问题没有收到任何评论或答案,我决定不排除其他库。因此,如果有支持枚举的C ++库,我将接受它。

点赞
用户5427663
用户5427663

由于这个问题没有得到任何评论或答案,我决定不排除其他库的可能性。因此,如果有一个支持枚举的 C++ 库,我会接受它。

Thor 库是 SFML 的扩展,支持 SFML 按键类型和字符串之间的转换。这将帮助你序列化枚举器并将它们作为字符串传递给 Lua——如果需要的话也可以将其转换回来。

2015-10-11 15:23:59
用户10363676
用户10363676

如果你只想将枚举转换为数字,请考虑使用<luabridge/detail/Vector.h>中的方法。

#include <LuaBridge/detail/Stack.h>
enum class LogLevels { LOG_1, LOG_2 }

namespace luabridge
{
    template <>
    struct Stack<LogLevels>
    {
        static void push(lua_State* L, LogLevels const& v) { lua_pushnumber( L, static_cast<int>(v) ); }
        static LogLevels get(lua_State* L, int index) { return LuaRef::fromStack(L, index); }
    };
}
2020-11-11 14:16:52
用户15253115
用户15253115

将以下内容添加到 Namespace 类中:

template<class T>
Namespace& addConstant(char const* name, T value)
{
    if (m_stackSize == 1)
    {
        throw std::logic_error("addConstant () called on global namespace");
    }

    assert(lua_istable(L, -1)); // Stack: namespace table (ns)

    Stack<T>::push(L,value); // Stack: ns, value
    rawsetfield(L, -2, name); // Stack: ns

    return *this;
}

然后使用:

getGlobalNamespace(L)
    .addNamespace("sf")
        .addNamespace("Event")
            .addConstant("KeyPressed",sf::Event::KeyPressed)
            //....
        .endNamespace()
    .endNamespace();
2021-07-06 07:16:40