title: Lua/Luajit: pause current Lua thread
body: <p>I am currently using Luajit along side Lua 5.1 and currently trying to register a function called "Wait" within the Lua C APIs. The main purpose of the function is to pause the current thread.</p>
  
  <p>Example usage: </p>
  
  <pre><code>print("Working");
  Wait()
  print("A");
  </code></pre>
  
  <p>However the function does not work as expected. Here is my C++ code.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;Windows.h&gt;
  
  extern "C" {
      #include "Luajit/luajit.h"
      #include &lt;Luajit/lua.h&gt;
      #include &lt;Luajit/lualib.h&gt;
      #include &lt;Luajit/lauxlib.h&gt;
  }
  
  
  static int wait(lua_State* lua) {
      return lua_yield(lua, 0);
  }
  
  int main() {
      lua_State* lua = luaL_newstate();
  
      if (!lua) {
          std::cout &lt;&lt; "Failed to create Lua state" &lt;&lt; std::endl;
          system("PAUSE");
          return -1;
      }
  
  luaL_openlibs(lua);
  lua_register(lua, "Wait", wait);
  
  lua_State* thread = lua_newthread(lua);
  
  if (!thread) {
      std::cout &lt;&lt; "Failed to create Lua thread" &lt;&lt; std::endl;
      system("PAUSE");
      return -1;
  }
  
  int status = luaL_loadfile(thread, "Z:/Projects/Visual Studio/Examples/Lua/Debug/Main.lua");
  
  if (status == LUA_ERRFILE) {
      std::cout &lt;&lt; "Failed to load file" &lt;&lt; std::endl;
      system("PAUSE");
      return -1;
  }
  
  int error = lua_pcall(thread, 0, 0, 0);
  
  if (error) {
      std::cout &lt;&lt; "Error: " &lt;&lt; lua_tostring(thread, 1) &lt;&lt; std::endl;
  }
  
  system("PAUSE");
  return 0;
  }
  </code></pre>
  
  <p>When I load up the Lua script I posted above I get the following output:</p>
  
  <pre><code>Working
  Error: attempt to yield across C-call boundary
  Press any key to continue . . .
  </code></pre>
  
  <p>I been programming in Lua for more than 4 years now. I just recently started using the C APIs and I never seen the C-call boundary error before. I did some Googling and ask friends and no one seems to be able to help me. Any idea what is wrong with my code?</p>
  
  <p>The error occur when I call the lua_yield(lua, 0) function in C++.</p>
  
  <p>I tried the answers of the following question and nothing seems to work.</p>
  
  <pre><code>http://stackoverflow.com/questions/8459459/lua-coroutine-error-tempt-to-yield-across-metamethod-c-call-boundary
  </code></pre>