2

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

  • get access to an instance of a lua class in C++
  • call functions on specific instance

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.

1
  • "in performance it requires a lot more to use C++ functions in lua than using lua functions in C++" What profiling did you use to determine this? As I understand, marshaling between the two languages works the same way either way. Depending of course on how you attach your C functions to Lua. Commented Jan 17, 2013 at 17:55

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry for disappearing, this is the answer I was looking for! thanks!
2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.