+static int clua_store_callback (lua_State *l, int idx) /* {{{ */
+{
+ static int callback_num = 0;
+ int callback_id;
+
+ /* XXX FIXME: Not thread-safe! */
+ callback_id = callback_num++;
+
+ if (idx < 0)
+ idx += lua_gettop (l) + 1;
+
+ lua_getfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* +1 = 1 */
+ if (!lua_istable (l, /* idx = */ -1))
+ {
+ lua_pop (l, /* nelems = */ 1); /* -1 = 0 */
+ lua_newtable (l); /* +1 = 1 */
+ lua_pushvalue (l, -1); /* +1 = 2 */
+ lua_setfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* -1 = 1 */
+ }
+
+ /* The table is now on top of the stack */
+ lua_pushinteger (l, (lua_Integer) callback_id); /* +1 = 2 */
+
+ /* Copy the function pointer */
+ lua_pushvalue (l, idx); /* +1 = 3 */
+ /* Lookup function if it's a string */
+ if (lua_isstring (l, /* idx = */ -1))
+ lua_gettable (l, LUA_GLOBALSINDEX); /* +-0 = 3 */
+
+ if (!lua_isfunction (l, /* idx = */ -1))
+ {
+ lua_pop (l, /* nelems = */ 3); /* -3 = 0 */
+ return (-1);
+ }
+
+ lua_settable (l, /* idx = */ -3); /* -2 = 1 */
+ lua_pop (l, /* nelems = */ 1); /* -1 = 0 */
+ return (callback_id);
+} /* }}} int clua_store_callback */
+
+static int clua_load_callback (lua_State *l, int callback_id) /* {{{ */
+{
+ lua_getfield (l, LUA_REGISTRYINDEX, "collectd_callbacks"); /* +1 */
+ if (!lua_istable (l, /* idx = */ -1))
+ {
+ lua_pop (l, /* nelems = */ 1); /* -1 */
+ return (-1);
+ }
+
+ lua_pushinteger (l, (lua_Integer) callback_id); /* + 1 */
+ lua_gettable (l, /* idx = */ -2); /* +-0 */
+
+ if (!lua_isfunction (l, -1))
+ {
+ lua_pop (l, /* nelems = */ 2); /* -2 */
+ return (-1);
+ }
+
+ /* Remove table */
+ lua_remove (l, /* idx = */ -2); /* -1 */
+ return (0);
+} /* }}} int clua_load_callback */
+