简体   繁体   English

如何从C / C ++访问lua脚本中的局部变量或调用局部函数?

[英]How could I access local variables or call local functions in lua scripts from C/C++?

If I define a "local" function, as such: 如果我定义“本地”函数,如下所示:

local function Dispatch(archive) coroutine.resume(yielder) end 局部函数Dispatch(存档)coroutine.resume(yielder)结束

...and I want to call this function from C++, I do not think I can use the lua_getglobal() call: ...并且我想从C ++调用此函数,我认为我不能使用lua_getglobal()调用:

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? 那么,如何在调用的准备工作中指定/推送本地函数“ Dispatch”? Again, I assume I cannot use the lua_getglobal() call, because the "Dispatch" function is defined as "local" to the m_pThreadState. 再次,我假设我不能使用lua_getglobal()调用,因为“ Dispatch”功能被定义为m_pThreadState的“本地”。 What do I do? 我该怎么办?

You cannot access local variables from C (aside from debug API, but I don't think that's what you want). 您无法从C访问局部变量(除调试API之外,但我认为这不是您想要的)。

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. 从Lua调用C函数并将本地函数作为参数传递。 Then you will have the function on the stack and will be able to call it from C (from within the C function). 然后,您将在堆栈上具有该函数,并将能够从C调用(从C函数内部)。 Now there is little point in doing that, I was just merely pointing at the way it could be done. 现在这样做没有什么意义,我只是指出可以完成的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM