使用C ++自动进行Lua绑定 [英] Automated Lua Binding using C++
问题描述
我正在构建一个简单的2D游戏引擎,并且它变得越来越大,因此无法公开Lua中的所有功能:因此,我正在尝试使该过程自动化一些, 无论如何,是否有一次从堆栈中获取所有n个参数(具有不同类型)并将它们直接注入C ++函数中. 我已经自动执行了args检查功能.功能绑定仍然有些棘手
I'm building a simple 2D game engine, and its getting bigger and bigger, exposing all of the function in Lua will be impossible: so I'm trying to automate a little bit the process, Is there anyway to get all the n arguments (with different types) from the stack at once and inject them directly into the C++ function. I already automated functions args checking. still the function binding which is a little bit tricky
例如: 我有更改子画面位置的普通代码:
For E.g: I have normal code for changing sprite position:
int LuaSprite::SetSpritePosition(lua_State* L)
{
Drawable* sprt = (Drawable*)lua_touserdata(L, 1);
int x = (int)lua_tonumber(L, 2);
int y = (int)lua_tonumber(L, 3);
sprt->setPosition(Vec2i(x, y));
return 0;
}
我想要实现的概念更像这样:
The concept that i want achieve is more less like this:
int LuaSprite::SetSpritePosition(lua_State* L)
{
LOAD_ARGS(Sprite*, int, int)
GET_ARG(1)->setPosition(Vec2i(GET_ARGS_FROM(1)));
LOAD_RETURN(true, x, y, 3);
return 3;
}
所以
- LOAD_ARGS将分别从堆栈中获得给定类型.
- GET_ARG(i)将在索引i处获得arg.
- GET_ARGS_FROM(i)将执行类似x,y,z,type
我并没有要求不可能做到的相同行为,但是至少有类似的事情
而且我敢肯定,仅使用普通" C ++不能实现这一点,并且我还需要一些魔术"宏.
我没有使用现成的自动Lua绑定库",因为有自定义结构,并且某些函数正在使用复杂的结构和类
我做了很多搜索,感到很迷茫.
I'm not requesting same behavior as it could be impossible to do, but something similar at least
And I'm sure that this isn't achievable only using 'plain' C++ and that I need also some 'magic' macros.
I'm not using the ready auto Lua binding "libraries" because there is custom structs and some functions are using complex structures and classes
I have done a lot of searching and I feel really lost.
推荐答案
尝试Luaaa( https://github. com/gengyong/luaaa ),它更轻巧,仅在一个头文件中实现.
try Luaaa(https://github.com/gengyong/luaaa), that's more lightweight, implement in only one single header file.
它完全满足您的要求.
It satisfied your requirements perfectly.
示例代码:
// include luaaa file
#include "luaaa.hpp"
using namespace luaaa;
// Your exists class
class Cat
{
public:
Cat();
virtual ~Cat();
public:
void setName(const std::string&);
const std::string& getName() const;
void eat(const std::list<std::string>& foods);
//...
private:
//...
};
lua_State * state; // create and init lua
// To export it:
LuaClass<Cat>(state, "AwesomeCat")
.ctor<std::string>();
.fun("setName", &Cat::setName);
.fun("getName", &Cat::getName);
.fun("eat", &Cat::eat);
.def("tag", "Cat");
您可以在此处找到更多详细信息( https://github.com/gengyong/luaaa )
我是该库的作者,强烈建议您尝试一下.如果有任何疑问,请随时提问.
I'm the author of this lib, I strongly recommend you have a try for it, if you have any questions, please feel free to ask.
这篇关于使用C ++自动进行Lua绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!