3

If I define a "local" function, as such:

local function Dispatch(archive) coroutine.resume(yielder) end

...and I want to call this function from C++, I do not think I can use the lua_getglobal() call:

m_pThreadState = lua_newthread(m_MasterLuaState);
//Load/define the above "Dispatch" routine local to this thread.
luaL_loadbuffer(m_pThreadState, m_ScriptBody, strlen(m_ScriptBody),"Console");
lua_getglobal(m_pThreadState, "Dispatch"); //UH-OH!! PROBLEM HERE!!
lua_pcall(m_pThreadState, 1, 0, 0);

So how do I specify/push the local function "Dispatch" in preperation for the call? Again, I assume I cannot use the lua_getglobal() call, because the "Dispatch" function is defined as "local" to the m_pThreadState. What do I do?

3
  • assign them to variables in the global table, or to a table accessible from the global table. Commented Apr 1, 2014 at 4:44
  • I don't think it's possible. But in case it is, you still shouldn't do it unless you like to confuse people just for the sake of being confuse people. (Because why would you do that instead of just making it global?) Commented Apr 1, 2014 at 5:57
  • Is there any specific reason you want the function to be local? Commented Apr 1, 2014 at 7:59

1 Answer 1

4

You cannot access local variables from C (aside from debug API, but I don't think that's what you want).

Local variables (and functions, since they're variables) are what they are - local, ie accessible only from within their surrounding scope.

So you're left with two options:

  • create a global variable
  • call a C function from Lua and pass the local function as a parameter. Then you will have the function on the stack and will be able to call it from C (from within the C function). Now there is little point in doing that, I was just merely pointing at the way it could be done.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, I think the second option is suitable but maybe it should edit the lua script. I want to find the local table from lua and manipulate it with C API. And finally I use the pattern-matching method to extract the table and write it into a new lua file to make it global. Thanks all the same.
@user3483507 this all looks terribly complicated. Perhaps you could describe your actual problem rather than your attempted solution? Perhaps there is a better approach to you problem, as what you're describing seems suboptimal at best.

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.