luabind没有运行我所定义的函数。

在一个名为 Test_Class 的类中,我有一个函数:

shoot_a_bullet(int damage)
{
    cout << "runned"; //我使用了 #using namespace std
}

我定义了以下代码:

luabind::module(myLuaState)[
    luabind::def("shoot_a_bullet", &Test_Class::shoot_a_bullet)
];

但是以下代码没有在屏幕上输出任何内容:

luaL_dostring(myLuaState,"shoot_a_bullet(134)\n");

PS:我在结尾处放了 cin.get(),这不是问题所在。

编辑:

我做这件事的主要目的是让我的脚本化的角色/敌人能够直接向一个保存子弹/效果/敌人等内容的向量中添加东西。

我不能使用静态函数是因为我需要主游戏阶段的指针来让它工作。

以下代码有效:

void print_hello(int number) {
    cout << "hello world and : " << number << endl << "number from main : " << x << endl;
}

int x; // 主函数中有一个全局值

int main()
{
    cin >> x;
    lua_State *myLuaState = luaL_newstate();

luabind::open(myLuaState);

luabind::module(myLuaState)[
    luabind::def("print_hello", print_hello)
];

luaL_dostring(
    myLuaState,
    "print_hello(123)\n"
    );
cin.get();
cin.get();

lua_close(myLuaState);
}

我需要一种在不是 main 类的类中执行此操作的方法。

点赞
用户2128694
用户2128694

你不能像这样注册成员函数。你所做的就像C++中的以下方式:

Test_Class::shoot_a_bullet(134);

例如,MSVC将其称为“非静态成员函数非法调用”,这确实是。

查看绑定类到Lua部分的Luabind文档,了解如何将一个类绑定到Lua。然后你需要创建这个类的一个对象,并在它上面调用函数,例如在Lua中使用 myobject:shoot_a_bullet(134): 为传递 myobject 作为第一个参数的语法糖)。

为了看到错误,你应该首先检查 luaL_dostring 的返回值。如果返回 true,则调用失败。消息被推入Lua堆栈作为字符串,可通过以下方法访问:

lua_tostring(myLuaState, -1);

在这种情况下,应该是这样的:

No matching overload found, candidates:
void shoot_a_bullet(Test_Class&)

解释:当你将成员函数注册为自由函数时,Luabind会在前面添加一个额外的引用参数,以便实际上将方法调用在为其传递的参数对象上。

2014-01-17 13:09:59