For me it seems that there is a quirk in luaL_unref.
There is a check at the beginning of luaL_unref:
if (ref >= 0)
But value 0 is used to store reference to the head of the freelist (there is a #define freelist 0 above)
So passing 0 to luaL_unref will cause some trouble.
It should not be a problem with correct usage of the API (luaL_ref never returns 0), but anyway this condition seems incorrect to me (should be "greater", not "greater and equal").