如何提高我 Lua 包装函数的简洁性?
2017-5-23 11:57:44
收藏:0
阅读:140
评论:1
我有以下模板特化,将C++函数包装到Lua中:
template<class ...Args>
struct Wrapper<void (*)(Args...)> {
using F = void (*)(Args...);
static int f (lua_State *L)
{
Lua lua(L);
// 获取函数指针。
F f = (F) lua_touserdata(L, lua_upvalueindex(1));
// 构建参数元组。
auto args = lua.CheckArgs<1, Args...>();
// 将函数应用于元组。
FunctionPointer<F> fp(f);
fp.Apply(args);
return 0;
}
};
template<class R, class ...Args>
struct Wrapper<R (*)(Args...)> {
using F = R (*)(Args...);
static int f (lua_State *L)
{
Lua lua(L);
// 获取函数指针。
F f = (F) lua_touserdata(L, lua_upvalueindex(1));
// 构建参数元组。
auto args = lua.CheckArgs<1, Args...>();
// 将函数应用于元组。
FunctionPointer<F> fp(f);
lua.Push( fp.Apply(args) );
return 1;
}
};
请注意它们的差异非常小。在第一个特化中,FunctionPointer<F>::Apply返回void。在第二个特化中,它的结果被推到Lua堆栈上。
我能把这两个特化组合成一个吗?
我意识到这可能看起来很吹毛求疵,但是在我的代码的其他地方,我不得不编写许多这样的包装器,因为包装的函数类型有所不同(自由函数、PMF、const或非const)。我一共有14个这样的特化。
这里有另外两个非常相似的特化,它们只通过PMF是否是const来区分:
template <typename Self, typename ...Args>
struct MethodWrapper<void (Self::*)(Args...) >
{
using F = void (Self::*)(Args...);
static int f (lua_State *L)
{
Lua lua(L);
F f = *(F *)lua_touserdata(L, lua_upvalueindex(1));
Self* self = lua.CheckPtr<Self>(1);
auto args = lua.CheckArgs<2, Args...>();
FunctionPointer<F> fp(f);
try {
fp.Apply(self, args);
} catch(std::exception& e) {
luaL_error(L, e.what());
}
return 0;
}
};
template <typename R, typename Self, typename ...Args>
struct MethodWrapper<R (Self::*)(Args...) const >
{
// 与上面完全相同
};
我能避免这种剪切和复制吗? (不使用宏)
相关但需要同样数量的特化:如何使用可变参数模板制作通用的Lua函数包装器?
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
你应该能够制作一个通用的函数器,它接受
fp、args和lua,并调用lua.Push(),当R是void时需要做偏特化处理,只调用函数并忽略 (void) 的结果。然后你可以这样调用它:ApplyAndPushIfNotVoid<R>()(lua, fp, args);