Question

In a class called Test_Class, I have a function :

shoot_a_bullet(int damage)  
{
    cout << "runned"; // i had #using namespace std
}

I had defined the code like following

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

And follow code didn't give me an output on screen

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

PS:I did put cin.get() at the end, that's not the problem.

edit: My main purpose of doing this is to let my scripted Character/Enemies able to directly adding stuff to a vector that hold bullets/effect/enemies and ect.
The reason i can't make the function static is because i need the pointer of main game stage to let it work.

following codes works fine

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

int x; //and the main with a global value

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);
}

I need a way to do this in a class that's not main

Was it helpful?

Solution

You can't register member functions like this. What your are doing is like the following in C++:

Test_Class::shoot_a_bullet(134);

MSVC for example calls that "illegal call of non-static member function", and that's exactly what it is.

Look at the section Binding classes to Lua in the Luabind documentation for how to bind a class to Lua. You then need to create an object of this class and call the function on it e.g. with myobject:shoot_a_bullet(134) in Lua (the : being syntactic sugar for passing myobject as first argument).

To see the error, you should first check the return value of luaL_dostring. If it returns true, the call failed. The message is pushed onto the Lua stack as as string, accessible with

lua_tostring(myLuaState, -1);

In this case it should be something like

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

Explanation: When you register a member function as a free one, luabind adds an extra reference parameter at the front so that the method is actually called on the argument object passed for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top