ltablib.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*
  2. ** $Id: ltablib.c,v 1.73 2014/07/29 16:01:00 roberto Exp roberto $
  3. ** Library for Table Manipulation
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <limits.h>
  7. #include <stddef.h>
  8. #define ltablib_c
  9. #define LUA_LIB
  10. #include "lua.h"
  11. #include "lauxlib.h"
  12. #include "lualib.h"
  13. /*
  14. ** Structure with table-access functions
  15. */
  16. typedef struct {
  17. int (*geti) (lua_State *L, int idx, lua_Integer n);
  18. void (*seti) (lua_State *L, int idx, lua_Integer n);
  19. } TabA;
  20. /*
  21. ** equivalent to 'lua_rawgeti', but not raw
  22. */
  23. static int geti (lua_State *L, int idx, lua_Integer n) {
  24. lua_pushinteger(L, n);
  25. return lua_gettable(L, idx); /* assume 'idx' is not negative */
  26. }
  27. /*
  28. ** equivalent to 'lua_rawseti', but not raw
  29. */
  30. static void seti (lua_State *L, int idx, lua_Integer n) {
  31. lua_pushinteger(L, n);
  32. lua_rotate(L, -2, 1); /* exchange key and value */
  33. lua_settable(L, idx); /* assume 'idx' is not negative */
  34. }
  35. /*
  36. ** Check that 'arg' has a table and set access functions in 'ta' to raw
  37. ** or non-raw according to the presence of corresponding metamethods.
  38. */
  39. static void checktab (lua_State *L, int arg, TabA *ta) {
  40. ta->geti = NULL; ta->seti = NULL;
  41. if (lua_getmetatable(L, arg)) {
  42. lua_pushliteral(L, "__index"); /* 'index' metamethod */
  43. if (lua_rawget(L, -2) != LUA_TNIL)
  44. ta->geti = geti;
  45. lua_pushliteral(L, "__newindex"); /* 'newindex' metamethod */
  46. if (lua_rawget(L, -3) != LUA_TNIL)
  47. ta->seti = seti;
  48. lua_pop(L, 3); /* pop metatable plus both metamethods */
  49. }
  50. if (ta->geti == NULL || ta->seti == NULL) {
  51. luaL_checktype(L, arg, LUA_TTABLE); /* must be table for raw methods */
  52. if (ta->geti == NULL) ta->geti = lua_rawgeti;
  53. if (ta->seti == NULL) ta->seti = lua_rawseti;
  54. }
  55. }
  56. #define aux_getn(L,n,ta) (checktab(L, n, ta), luaL_len(L, n))
  57. #if defined(LUA_COMPAT_MAXN)
  58. static int maxn (lua_State *L) {
  59. lua_Number max = 0;
  60. luaL_checktype(L, 1, LUA_TTABLE);
  61. lua_pushnil(L); /* first key */
  62. while (lua_next(L, 1)) {
  63. lua_pop(L, 1); /* remove value */
  64. if (lua_type(L, -1) == LUA_TNUMBER) {
  65. lua_Number v = lua_tonumber(L, -1);
  66. if (v > max) max = v;
  67. }
  68. }
  69. lua_pushnumber(L, max);
  70. return 1;
  71. }
  72. #endif
  73. static int tinsert (lua_State *L) {
  74. TabA ta;
  75. lua_Integer e = aux_getn(L, 1, &ta) + 1; /* first empty element */
  76. lua_Integer pos; /* where to insert new element */
  77. switch (lua_gettop(L)) {
  78. case 2: { /* called with only 2 arguments */
  79. pos = e; /* insert new element at the end */
  80. break;
  81. }
  82. case 3: {
  83. lua_Integer i;
  84. pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */
  85. luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds");
  86. for (i = e; i > pos; i--) { /* move up elements */
  87. (*ta.geti)(L, 1, i - 1);
  88. (*ta.seti)(L, 1, i); /* t[i] = t[i - 1] */
  89. }
  90. break;
  91. }
  92. default: {
  93. return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
  94. }
  95. }
  96. (*ta.seti)(L, 1, pos); /* t[pos] = v */
  97. return 0;
  98. }
  99. static int tremove (lua_State *L) {
  100. TabA ta;
  101. lua_Integer size = aux_getn(L, 1, &ta);
  102. lua_Integer pos = luaL_optinteger(L, 2, size);
  103. if (pos != size) /* validate 'pos' if given */
  104. luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds");
  105. (*ta.geti)(L, 1, pos); /* result = t[pos] */
  106. for ( ; pos < size; pos++) {
  107. (*ta.geti)(L, 1, pos + 1);
  108. (*ta.seti)(L, 1, pos); /* t[pos] = t[pos + 1] */
  109. }
  110. lua_pushnil(L);
  111. (*ta.seti)(L, 1, pos); /* t[pos] = nil */
  112. return 1;
  113. }
  114. static int tmove (lua_State *L) {
  115. TabA ta;
  116. lua_Integer f = luaL_checkinteger(L, 2);
  117. lua_Integer e = luaL_checkinteger(L, 3);
  118. lua_Integer t = luaL_checkinteger(L, 4);
  119. int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */
  120. /* the following restriction avoids several problems with overflows */
  121. luaL_argcheck(L, f > 0, 2, "initial position must be positive");
  122. if (e >= f) { /* otherwise, nothing to move */
  123. lua_Integer n, i;
  124. ta.geti = (!luaL_getmetafield(L, 1, "__index"))
  125. ? (luaL_checktype(L, 1, LUA_TTABLE), lua_rawgeti)
  126. : geti;
  127. ta.seti = (!luaL_getmetafield(L, tt, "__newindex"))
  128. ? (luaL_checktype(L, tt, LUA_TTABLE), lua_rawseti)
  129. : seti;
  130. n = e - f + 1; /* number of elements to move */
  131. if (t > f) {
  132. for (i = n - 1; i >= 0; i--) {
  133. (*ta.geti)(L, 1, f + i);
  134. (*ta.seti)(L, tt, t + i);
  135. }
  136. }
  137. else {
  138. for (i = 0; i < n; i++) {
  139. (*ta.geti)(L, 1, f + i);
  140. (*ta.seti)(L, tt, t + i);
  141. }
  142. }
  143. }
  144. lua_pushvalue(L, tt); /* return "to table" */
  145. return 1;
  146. }
  147. static void addfield (lua_State *L, luaL_Buffer *b, TabA *ta, lua_Integer i) {
  148. (*ta->geti)(L, 1, i);
  149. if (!lua_isstring(L, -1))
  150. luaL_error(L, "invalid value (%s) at index %d in table for "
  151. LUA_QL("concat"), luaL_typename(L, -1), i);
  152. luaL_addvalue(b);
  153. }
  154. static int tconcat (lua_State *L) {
  155. TabA ta;
  156. luaL_Buffer b;
  157. size_t lsep;
  158. lua_Integer i, last;
  159. const char *sep = luaL_optlstring(L, 2, "", &lsep);
  160. checktab(L, 1, &ta);
  161. i = luaL_optinteger(L, 3, 1);
  162. last = luaL_opt(L, luaL_checkinteger, 4, luaL_len(L, 1));
  163. luaL_buffinit(L, &b);
  164. for (; i < last; i++) {
  165. addfield(L, &b, &ta, i);
  166. luaL_addlstring(&b, sep, lsep);
  167. }
  168. if (i == last) /* add last value (if interval was not empty) */
  169. addfield(L, &b, &ta, i);
  170. luaL_pushresult(&b);
  171. return 1;
  172. }
  173. /*
  174. ** {======================================================
  175. ** Pack/unpack
  176. ** =======================================================
  177. */
  178. static int pack (lua_State *L) {
  179. int i;
  180. int n = lua_gettop(L); /* number of elements to pack */
  181. lua_createtable(L, n, 1); /* create result table */
  182. lua_insert(L, 1); /* put it at index 1 */
  183. for (i = n; i >= 1; i--) /* assign elements */
  184. lua_rawseti(L, 1, i);
  185. lua_pushinteger(L, n);
  186. lua_setfield(L, 1, "n"); /* t.n = number of elements */
  187. return 1; /* return table */
  188. }
  189. static int unpack (lua_State *L) {
  190. TabA ta;
  191. lua_Integer i, e;
  192. lua_Unsigned n;
  193. checktab(L, 1, &ta);
  194. i = luaL_optinteger(L, 2, 1);
  195. e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
  196. if (i > e) return 0; /* empty range */
  197. n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */
  198. if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n)))
  199. return luaL_error(L, "too many results to unpack");
  200. do { /* must have at least one element */
  201. (*ta.geti)(L, 1, i); /* push arg[i..e] */
  202. } while (i++ < e);
  203. return (int)n;
  204. }
  205. /* }====================================================== */
  206. /*
  207. ** {======================================================
  208. ** Quicksort
  209. ** (based on `Algorithms in MODULA-3', Robert Sedgewick;
  210. ** Addison-Wesley, 1993.)
  211. ** =======================================================
  212. */
  213. static void set2 (lua_State *L, TabA *ta, int i, int j) {
  214. (*ta->seti)(L, 1, i);
  215. (*ta->seti)(L, 1, j);
  216. }
  217. static int sort_comp (lua_State *L, int a, int b) {
  218. if (!lua_isnil(L, 2)) { /* function? */
  219. int res;
  220. lua_pushvalue(L, 2);
  221. lua_pushvalue(L, a-1); /* -1 to compensate function */
  222. lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */
  223. lua_call(L, 2, 1);
  224. res = lua_toboolean(L, -1);
  225. lua_pop(L, 1);
  226. return res;
  227. }
  228. else /* a < b? */
  229. return lua_compare(L, a, b, LUA_OPLT);
  230. }
  231. static void auxsort (lua_State *L, TabA *ta, int l, int u) {
  232. while (l < u) { /* for tail recursion */
  233. int i, j;
  234. /* sort elements a[l], a[(l+u)/2] and a[u] */
  235. (*ta->geti)(L, 1, l);
  236. (*ta->geti)(L, 1, u);
  237. if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */
  238. set2(L, ta, l, u); /* swap a[l] - a[u] */
  239. else
  240. lua_pop(L, 2);
  241. if (u-l == 1) break; /* only 2 elements */
  242. i = (l+u)/2;
  243. (*ta->geti)(L, 1, i);
  244. (*ta->geti)(L, 1, l);
  245. if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */
  246. set2(L, ta, i, l);
  247. else {
  248. lua_pop(L, 1); /* remove a[l] */
  249. (*ta->geti)(L, 1, u);
  250. if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */
  251. set2(L, ta, i, u);
  252. else
  253. lua_pop(L, 2);
  254. }
  255. if (u-l == 2) break; /* only 3 elements */
  256. (*ta->geti)(L, 1, i); /* Pivot */
  257. lua_pushvalue(L, -1);
  258. (*ta->geti)(L, 1, u-1);
  259. set2(L, ta, i, u-1);
  260. /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
  261. i = l; j = u-1;
  262. for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */
  263. /* repeat ++i until a[i] >= P */
  264. while ((*ta->geti)(L, 1, ++i), sort_comp(L, -1, -2)) {
  265. if (i>=u) luaL_error(L, "invalid order function for sorting");
  266. lua_pop(L, 1); /* remove a[i] */
  267. }
  268. /* repeat --j until a[j] <= P */
  269. while ((*ta->geti)(L, 1, --j), sort_comp(L, -3, -1)) {
  270. if (j<=l) luaL_error(L, "invalid order function for sorting");
  271. lua_pop(L, 1); /* remove a[j] */
  272. }
  273. if (j<i) {
  274. lua_pop(L, 3); /* pop pivot, a[i], a[j] */
  275. break;
  276. }
  277. set2(L, ta, i, j);
  278. }
  279. (*ta->geti)(L, 1, u-1);
  280. (*ta->geti)(L, 1, i);
  281. set2(L, ta, u-1, i); /* swap pivot (a[u-1]) with a[i] */
  282. /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
  283. /* adjust so that smaller half is in [j..i] and larger one in [l..u] */
  284. if (i-l < u-i) {
  285. j=l; i=i-1; l=i+2;
  286. }
  287. else {
  288. j=i+1; i=u; u=j-2;
  289. }
  290. auxsort(L, ta, j, i); /* call recursively the smaller one */
  291. } /* repeat the routine for the larger one */
  292. }
  293. static int sort (lua_State *L) {
  294. TabA ta;
  295. int n = (int)aux_getn(L, 1, &ta);
  296. luaL_checkstack(L, 50, ""); /* assume array is smaller than 2^50 */
  297. if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
  298. luaL_checktype(L, 2, LUA_TFUNCTION);
  299. lua_settop(L, 2); /* make sure there are two arguments */
  300. auxsort(L, &ta, 1, n);
  301. return 0;
  302. }
  303. /* }====================================================== */
  304. static const luaL_Reg tab_funcs[] = {
  305. {"concat", tconcat},
  306. #if defined(LUA_COMPAT_MAXN)
  307. {"maxn", maxn},
  308. #endif
  309. {"insert", tinsert},
  310. {"pack", pack},
  311. {"unpack", unpack},
  312. {"remove", tremove},
  313. {"move", tmove},
  314. {"sort", sort},
  315. {NULL, NULL}
  316. };
  317. LUAMOD_API int luaopen_table (lua_State *L) {
  318. luaL_newlib(L, tab_funcs);
  319. #if defined(LUA_COMPAT_UNPACK)
  320. /* _G.unpack = table.unpack */
  321. lua_getfield(L, -1, "unpack");
  322. lua_setglobal(L, "unpack");
  323. #endif
  324. return 1;
  325. }