title: Call a Lua function from C++
body: <p>I have google high and low and found examples, but none of them seems to work (Lua 5.2).</p>
  
  <p>I have a simple function in Lua</p>
  
  <pre><code>function onData ( data )
    print ( data )
  end
  </code></pre>
  
  <p>I want to call <code>onData</code> from C++ and tried this:</p>
  
  <pre><code>// Create new Lua state
  L = luaL_newstate();
  
  // Load all Lua libraries
  luaL_openlibs(L);
  
  // Create co-routine
  CO = lua_newthread(L);
  
  // Load and compile script
  AnsiString script(Frame-&gt;Script_Edit-&gt;Text);
  if (luaL_loadbuffer(CO,script.c_str(),script.Length(),AnsiString(Name).c_str()) == LUA_OK) {
    Compiled = true;
  } else {
    cs_error(CO, "Compiler error: ");    // Print compiler error
    Compiled = false;
  }
  
  
  // Script compiled and ready?
  if (Compiled == true) {
    lua_getglobal(CO, "onData");    // &lt;-------- Doesn't find the function
    if( !lua_isfunction(CO,-1)) {
      lua_pop(CO,1);
      return;
    }
    lua_pushlstring(CO,data,len);
    lua_resume(CO,NULL,0)
  }
  </code></pre>
  
  <p>As you can see I'm starting my script as a co-routine so I can use the <code>lua_yield()</code> function on it. I have tried to look for the function in both the <code>L</code> and <code>CO</code> states.</p>