Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register C++ function in Lua?

Tags:

c++

lua

I am trying to register a c++ function in Lua.

But getting this error:

CScript.cpp|39|error: argument of type 'int (CScript::)(lua_State*)' does not match 'int (*)(lua_State*)'|

EDIT:

int CApp::SetDisplayMode(int Width, int Height, int Depth)
{
    this->Screen_Width = Width;
    this->Screen_Height = Height;
    this->Screen_Depth = Depth;

    return 0;
}

int CScript::Lua_SetDisplayMode(lua_State* L)
{
  // We need at least one parameter
  int n = lua_gettop(L);
  if(n < 0)
  {
    lua_pushstring(L, "Not enough parameter.");
    lua_error(L);
  }

  int width = lua_tointeger(L, 1);
  int height = lua_tointeger(L, 2);
  int depth = lua_tointeger(L, 3);

  lua_pushinteger(L, App->SetDisplayMode(width, height, depth));

  return 0;
}

And in main:

lua_register(L, "setDisplayMode", Lua_SetDisplayMode);
like image 979
Cobra Avatar asked May 01 '26 08:05

Cobra


2 Answers

You can not use a method of a class as a normal function, unless it is declared static. You have to define a normal function, which finds out what object you want the method to be called in, and then call the method.

The main reason it's not possible to use a class method as a callback from a C function (and remember that the Lua API is a pure C library), is because the computer doesn't know which object the method should be called on.

like image 196
Some programmer dude Avatar answered May 03 '26 17:05

Some programmer dude


The answer is actually surprisingly simple; if you use lua_pushcclosure instead of lua_pushcfunction, you can pass parameters to your called function:

    lua_pushlightuserdata(_state, this);
    lua_pushcclosure(_state, &MyClass::lua_static_helper, 1);

    int MyClass::lua_static_helper(lua_State *state) {
        MyClass *klass = (MyClass *) lua_touserdata(state, lua_upvalueindex(1));
        return klass->lua_member_method(state);
    }
like image 22
Phil Lello Avatar answered May 03 '26 16:05

Phil Lello