leafblight
leafblight

Reputation: 33

accessing lua class functions in C++

I have come upon a problem with binding C++ and Lua. I have implemented a simple class system in Lua that makes me able to create an "instance" of a lua class from another lua file using

require 'classname'
m_newObj = classname() --"classname() creates a new instance

then I can access functions in m_newObj using

m_newObj:functionname(parameter)

This works perfectly fine, but I want to be able to access an instance of a lua class from C++ code.

Normally you can create access to lua functions in C++ using

lua_State* pL = luaL_newState();
...
lua_getglobal(pL, "functionName");
lua_call(pL,0,0);

But this only calls a function in a luafile, it does not call that specific function on a specific instance of the "class".

So basically what I want to do is

The reason why I want to do this is because I've discovered that in performance it requires a lot more to use C++ functions in lua than using lua functions in C++, So to be able to use lua to extend entities without having the lua code call a lot of C++ functions I need to get access to lua classes in C++ instead of getting access to C++ classes in lua.

Upvotes: 2

Views: 918

Answers (2)

furq
furq

Reputation: 5788

Push your class onto the stack, lua_getfield() the function from it, and then copy your class back onto the top of the stack before calling the function. Something like this:

int nresults = 1;                  // number of results from your Lua function

lua_getglobal(L, "classname");
lua_getfield(L, -1, "funcname");
lua_pushvalue(L, -2);              // push a copy of the class to the top of the stack
lua_call(L, 1, nresults);          // equivalent to classname.funcname(classname)

Upvotes: 2

Nicol Bolas
Nicol Bolas

Reputation: 473437

m_newObj:functionname(parameter)

This is syntactic sugar for this:

m_newObj.functionname(m_newObj, parameter)

So just do the equivalent of that from your C++ code.

Upvotes: 2

Related Questions