static int getboolfield (lv_State *L, const char *key) { int res; lv_getfield(L, -1, key); res = lv_isnil(L, -1) ? -1 : lv_toboolean(L, -1); lv_pop(L, 1); return res; }
static int sort_comp (lv_State *L, int a, int b) { if (!lv_isnil(L, 2)) { /* function? */ int res; lv_pushvalue(L, 2); lv_pushvalue(L, a-1); /* -1 to compensate function */ lv_pushvalue(L, b-2); /* -2 to compensate function and `a' */ lv_call(L, 2, 1); res = lv_toboolean(L, -1); lv_pop(L, 1); return res; } else /* a < b? */ return lv_lessthan(L, a, b); }
static int foreach (lv_State *L) { lv_clearFirstTableValue(L); lvL_checktype(L, 1, LV_TTABLE); lvL_checktype(L, 2, LV_TFUNCTION); lv_pushnil(L); /* first key */ while (lv_next(L, 1)) { lv_pushvalue(L, 2); /* function */ lv_pushvalue(L, -3); /* key */ lv_pushvalue(L, -3); /* value */ lv_call(L, 2, 1); if (!lv_isnil(L, -1)) return 1; lv_pop(L, 2); /* remove value and result */ } return 0; }
static int foreachi (lv_State *L) { lv_clearFirstTableValue(L); int i; int n = aux_getn(L, 1); lvL_checktype(L, 2, LV_TFUNCTION); for (i=1; i <= n; i++) { lv_pushvalue(L, 2); /* function */ lv_pushinteger(L, i); /* 1st argument */ lv_rawgeti(L, 1, i); /* 2nd argument */ lv_call(L, 2, 1); if (!lv_isnil(L, -1)) return 1; lv_pop(L, 1); /* remove nil result */ } return 0; }