使用 C API 和模板将任意 C/C++ 类型推入 Lua 栈

Lua 有许多函数可用于将值推入堆栈。我尝试使用模板来完成这个任务,但似乎遇到了一些问题。我了解到在使用模板时代码是从模板创建的。因此,我猜测问题在于使用的类型与可能使用的 Lua 函数的参数类型不匹配。有没有办法解决这个问题?我对 C++ 还比较新,如果有人能够找到技术名称或解决这个问题的过程,那就太棒了!我在网上找不到使用模板解决此问题的任何信息。我正在使用枚举来避免直接使用 C++ 检查类型,因为显然这有点复杂和/或不保证能够工作。提前感谢!

enum class LuaType {
    nil = LUA_TNIL, boolean = LUA_TBOOLEAN, lightUserData = LUA_TLIGHTUSERDATA,
    number = LUA_TNUMBER, string = LUA_TSTRING, table = LUA_TTABLE, function = LUA_TFUNCTION,
    userdata = LUA_TUSERDATA, thread = LUA_TTHREAD, numtags = LUA_NUMTAGS
};

template<typename T>
    void createGlobalVariable(const char* name, LuaType type, T value = NULL) {

        switch (type) {

        case LuaType::nil:
            lua_pushnil(this->state.get());
            break;
        case LuaType::boolean:
            lua_pushboolean(this->state.get(), value);
            break;
        case LuaType::number:
            lua_pushnumber(this->state.get(), value);
            break;
        case LuaType::string:
            lua_pushstring(this->state.get(), value);
            break;
        case LuaType::table:
            lua_newtable(this->state.get());
            break;

        }

        lua_setglobal(this->state.get(), name);
    }

编辑: 当进行函数重载时,它看起来像下面这样,但我希望有更好的方法来解决它。

void createGlobalVariable(const char* name, double value) {
    lua_pushnumber(this->state.get(), value);
    lua_setglobal(this->state.get(), name);
}

void createGlobalVariable(const char* name, int value) {
    lua_pushinteger(this->state.get(), value);
    lua_setglobal(this->state.get(), name);
}

void createGlobalVariable(const char* name, const char* value) {
    lua_pushstring(this->state.get(), value);
    lua_setglobal(this->state.get(), name);
}

void createGlobalVariable(const char* name, void* value) {
    lua_pushlightuserdata(this->state.get(), value);
    lua_setglobal(this->state.get(), name);
}

void createGlobalVariable(const char* name, bool value) {
    lua_pushboolean(this->state.get(), value);
    lua_setglobal(this->state.get(), name);
}
点赞