title: MemFault in GC when calling back a closure from C
body: <p>I working with Keil, MDK-ARM Pro 4.71 for a Cortex-M3 target(STM32F107).</p>
  
  <p>I have compiled the Lua interpreter and a Lua "timer" module that interfaces the chip's timers. I'd like to call a lua function when the timer is elapsed.</p>
  
  <p>Here is a sample use :</p>
  
  <pre><code>t = timer.open()
  t.event = function() print("Bing !") end
  t:start()
  </code></pre>
  
  <p>Until here, everything works fine :-) ! I see the "Bing !" message being printed each time the timer elapses.</p>
  
  <p>Now if I use a closure :</p>
  
  <pre><code>t = timer.open()
  i = 0
  t.event = function() i = i + 1; print(i); end
  t:start()
  </code></pre>
  
  <p>I'm having a bad memory access in the GC after some amount of timer's updates. Since it's an embedded context with very few memory, I may be running out of memory quite fast if there is a leak.</p>
  
  <p>Here is the "t.event" setter (ELIB_TIMER is a C structure representing my timer) :</p>
  
  <pre><code>static int ElibTimerSetEvent(lua_State* L)
  {
     ELIB_TIMER* pTimer_X = ElibCheckTimer(L, 1, TRUE);
  
     if (pTimer_X-&gt;LuaFuncKey_i != LUA_REFNIL)
     {
        luaL_unref(L, LUA_REGISTRYINDEX, pTimer_X-&gt;LuaFuncKey_i);
        pTimer_X-&gt;LuaFuncKey_i = LUA_REFNIL;
     }
  
     if (!lua_isnil(L, 2))
     {
        pTimer_X-&gt;LuaFuncKey_i = luaL_ref(L, LUA_REGISTRYINDEX);
     }
  
     return 0;
  }
  </code></pre>
  
  <p>And here is the native callback implementation :</p>
  
  <pre><code>static void ElibTimerEventHandler(SYSEVT_HANDLE Event_H)
  {
     ELIB_TIMER* pTimer_X = (ELIB_TIMER*)SWLIB_SYSEVT_GetSideData(Event_H);
     lua_State* L = pTimer_X-&gt;L;
     int i = lua_gettop(L);
     if (pTimer_X-&gt;LuaFuncKey_i != LUA_REFNIL)
     {
        lua_rawgeti(L, LUA_REGISTRYINDEX, pTimer_X-&gt;LuaFuncKey_i);
        lua_call(L, 0, 0);
        lua_settop(L, i);
     }
  }
  </code></pre>
  
  <p>This is synchronized externally, so this isn't a synchronization issue.</p>
  
  <p>Am I doing something wrong ?</p>
  
  <p>EDIT</p>
  
  <p>Here is the callstack (with a lua_pcall instead of lua_call, but it is the same). The first line is my hard fault handler.</p>
  
  <p><img src="https://i.stack.imgur.com/dMawN.png" alt="Lua call stack"></p>