3 ** Library for Table Manipulation
4 ** See Copyright Notice in lua.h
24 ** Operations that an object must define to mimic a table
25 ** (some functions only need some of them)
27 #define TAB_R 1 /* read */
28 #define TAB_W 2 /* write */
29 #define TAB_L 4 /* length */
30 #define TAB_RW (TAB_R | TAB_W) /* read/write */
33 #define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n))
36 static int checkfield(lua_State
*L
, const char *key
, int n
) {
37 lua_pushstring(L
, key
);
38 return (lua_rawget(L
, -n
) != LUA_TNIL
);
43 ** Check that 'arg' either is a table or can behave like one (that is,
44 ** has a metatable with the required metamethods)
46 static void checktab(lua_State
*L
, int arg
, int what
) {
47 if (lua_type(L
, arg
) != LUA_TTABLE
) { /* is it not a table? */
48 int n
= 1; /* number of elements to pop */
49 if (lua_getmetatable(L
, arg
) && /* must have metatable */
50 (!(what
& TAB_R
) || checkfield(L
, "__index", ++n
)) &&
51 (!(what
& TAB_W
) || checkfield(L
, "__newindex", ++n
)) &&
52 (!(what
& TAB_L
) || checkfield(L
, "__len", ++n
))) {
53 lua_pop(L
, n
); /* pop metatable and tested metamethods */
55 luaL_checktype(L
, arg
, LUA_TTABLE
); /* force an error */
60 static int tinsert(lua_State
*L
) {
61 lua_Integer pos
; /* where to insert new element */
62 lua_Integer e
= aux_getn(L
, 1, TAB_RW
);
63 e
= luaL_intop(+, e
, 1); /* first empty element */
64 switch (lua_gettop(L
)) {
65 case 2: { /* called with only 2 arguments */
66 pos
= e
; /* insert new element at the end */
71 pos
= luaL_checkinteger(L
, 2); /* 2nd argument is the position */
72 /* check whether 'pos' is in [1, e] */
73 luaL_argcheck(L
, (lua_Unsigned
)pos
- 1u < (lua_Unsigned
)e
, 2,
74 "position out of bounds");
75 for (i
= e
; i
> pos
; i
--) { /* move up elements */
76 lua_geti(L
, 1, i
- 1);
77 lua_seti(L
, 1, i
); /* t[i] = t[i - 1] */
82 return luaL_error(L
, "wrong number of arguments to 'insert'");
85 lua_seti(L
, 1, pos
); /* t[pos] = v */
90 static int tremove(lua_State
*L
) {
91 lua_Integer size
= aux_getn(L
, 1, TAB_RW
);
92 lua_Integer pos
= luaL_optinteger(L
, 2, size
);
93 if (pos
!= size
) /* validate 'pos' if given */
94 /* check whether 'pos' is in [1, size + 1] */
95 luaL_argcheck(L
, (lua_Unsigned
)pos
- 1u <= (lua_Unsigned
)size
, 2,
96 "position out of bounds");
97 lua_geti(L
, 1, pos
); /* result = t[pos] */
98 for (; pos
< size
; pos
++) {
99 lua_geti(L
, 1, pos
+ 1);
100 lua_seti(L
, 1, pos
); /* t[pos] = t[pos + 1] */
103 lua_seti(L
, 1, pos
); /* remove entry t[pos] */
109 ** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever
110 ** possible, copy in increasing order, which is better for rehashing.
111 ** "possible" means destination after original range, or smaller
112 ** than origin, or copying to another table.
114 static int tmove(lua_State
*L
) {
115 lua_Integer f
= luaL_checkinteger(L
, 2);
116 lua_Integer e
= luaL_checkinteger(L
, 3);
117 lua_Integer t
= luaL_checkinteger(L
, 4);
118 int tt
= !lua_isnoneornil(L
, 5) ? 5 : 1; /* destination table */
119 checktab(L
, 1, TAB_R
);
120 checktab(L
, tt
, TAB_W
);
121 if (e
>= f
) { /* otherwise, nothing to move */
123 luaL_argcheck(L
, f
> 0 || e
< LUA_MAXINTEGER
+ f
, 3,
124 "too many elements to move");
125 n
= e
- f
+ 1; /* number of elements to move */
126 luaL_argcheck(L
, t
<= LUA_MAXINTEGER
- n
+ 1, 4,
127 "destination wrap around");
128 if (t
> e
|| t
<= f
|| (tt
!= 1 && !lua_compare(L
, 1, tt
, LUA_OPEQ
))) {
129 for (i
= 0; i
< n
; i
++) {
130 lua_geti(L
, 1, f
+ i
);
131 lua_seti(L
, tt
, t
+ i
);
134 for (i
= n
- 1; i
>= 0; i
--) {
135 lua_geti(L
, 1, f
+ i
);
136 lua_seti(L
, tt
, t
+ i
);
140 lua_pushvalue(L
, tt
); /* return destination table */
145 static void addfield(lua_State
*L
, luaL_Buffer
*b
, lua_Integer i
) {
147 if (l_unlikely(!lua_isstring(L
, -1)))
148 luaL_error(L
, "invalid value (%s) at index %I in table for 'concat'",
149 luaL_typename(L
, -1), (LUAI_UACINT
)i
);
154 static int tconcat(lua_State
*L
) {
156 lua_Integer last
= aux_getn(L
, 1, TAB_R
);
158 const char *sep
= luaL_optlstring(L
, 2, "", &lsep
);
159 lua_Integer i
= luaL_optinteger(L
, 3, 1);
160 last
= luaL_optinteger(L
, 4, last
);
161 luaL_buffinit(L
, &b
);
162 for (; i
< last
; i
++) {
164 luaL_addlstring(&b
, sep
, lsep
);
166 if (i
== last
) /* add last value (if interval was not empty) */
174 ** {======================================================
176 ** =======================================================
179 static int tpack(lua_State
*L
) {
181 int n
= lua_gettop(L
); /* number of elements to pack */
182 lua_createtable(L
, n
, 1); /* create result table */
183 lua_insert(L
, 1); /* put it at index 1 */
184 for (i
= n
; i
>= 1; i
--) /* assign elements */
186 lua_pushinteger(L
, n
);
187 lua_setfield(L
, 1, "n"); /* t.n = number of elements */
188 return 1; /* return table */
192 static int tunpack(lua_State
*L
) {
194 lua_Integer i
= luaL_optinteger(L
, 2, 1);
195 lua_Integer 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 (l_unlikely(n
>= (unsigned int)INT_MAX
||
199 !lua_checkstack(L
, (int)(++n
))))
200 return luaL_error(L
, "too many results to unpack");
201 for (; i
< e
; i
++) { /* push arg[i..e - 1] (to avoid overflows) */
204 lua_geti(L
, 1, e
); /* push last element */
208 /* }====================================================== */
213 ** {======================================================
215 ** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
216 ** Addison-Wesley, 1993.)
217 ** =======================================================
221 /* type for array indices */
222 typedef unsigned int IdxT
;
226 ** Produce a "random" 'unsigned int' to randomize pivot choice. This
227 ** macro is used only when 'sort' detects a big imbalance in the result
228 ** of a partition. (If you don't want/need this "randomness", ~0 is a
231 #if !defined(l_randomizePivot) /* { */
235 /* size of 'e' measured in number of 'unsigned int's */
236 #define sof(e) (sizeof(e) / sizeof(unsigned int))
239 ** Use 'time' and 'clock' as sources of "randomness". Because we don't
240 ** know the types 'clock_t' and 'time_t', we cannot cast them to
241 ** anything without risking overflows. A safe way to use their values
242 ** is to copy them to an array of a known type and use the array values.
244 static unsigned int l_randomizePivot(void) {
246 time_t t
= time(NULL
);
247 unsigned int buff
[sof(c
) + sof(t
)];
248 unsigned int i
, rnd
= 0;
249 memcpy(buff
, &c
, sof(c
) * sizeof(unsigned int));
250 memcpy(buff
+ sof(c
), &t
, sof(t
) * sizeof(unsigned int));
251 for (i
= 0; i
< sof(buff
); i
++)
259 /* arrays larger than 'RANLIMIT' may use randomized pivots */
260 #define RANLIMIT 100u
263 static void set2(lua_State
*L
, IdxT i
, IdxT j
) {
270 ** Return true iff value at stack index 'a' is less than the value at
271 ** index 'b' (according to the order of the sort).
273 static int sort_comp(lua_State
*L
, int a
, int b
) {
274 if (lua_isnil(L
, 2)) /* no function? */
275 return lua_compare(L
, a
, b
, LUA_OPLT
); /* a < b */
276 else { /* function */
278 lua_pushvalue(L
, 2); /* push function */
279 lua_pushvalue(L
, a
- 1); /* -1 to compensate function */
280 lua_pushvalue(L
, b
- 2); /* -2 to compensate function and 'a' */
281 lua_call(L
, 2, 1); /* call function */
282 res
= lua_toboolean(L
, -1); /* get result */
283 lua_pop(L
, 1); /* pop result */
290 ** Does the partition: Pivot P is at the top of the stack.
291 ** precondition: a[lo] <= P == a[up-1] <= a[up],
292 ** so it only needs to do the partition from lo + 1 to up - 2.
293 ** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]
296 static IdxT
partition(lua_State
*L
, IdxT lo
, IdxT up
) {
297 IdxT i
= lo
; /* will be incremented before first use */
298 IdxT j
= up
- 1; /* will be decremented before first use */
299 /* loop invariant: a[lo .. i] <= P <= a[j .. up] */
301 /* next loop: repeat ++i while a[i] < P */
302 while ((void)lua_geti(L
, 1, ++i
), sort_comp(L
, -1, -2)) {
303 if (l_unlikely(i
== up
- 1)) /* a[i] < P but a[up - 1] == P ?? */
304 luaL_error(L
, "invalid order function for sorting");
305 lua_pop(L
, 1); /* remove a[i] */
307 /* after the loop, a[i] >= P and a[lo .. i - 1] < P */
308 /* next loop: repeat --j while P < a[j] */
309 while ((void)lua_geti(L
, 1, --j
), sort_comp(L
, -3, -1)) {
310 if (l_unlikely(j
< i
)) /* j < i but a[j] > P ?? */
311 luaL_error(L
, "invalid order function for sorting");
312 lua_pop(L
, 1); /* remove a[j] */
314 /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */
315 if (j
< i
) { /* no elements out of place? */
316 /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */
317 lua_pop(L
, 1); /* pop a[j] */
318 /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */
322 /* otherwise, swap a[i] - a[j] to restore invariant and repeat */
329 ** Choose an element in the middle (2nd-3th quarters) of [lo,up]
330 ** "randomized" by 'rnd'
332 static IdxT
choosePivot(IdxT lo
, IdxT up
, unsigned int rnd
) {
333 IdxT r4
= (up
- lo
) / 4; /* range/4 */
334 IdxT p
= rnd
% (r4
* 2) + (lo
+ r4
);
335 lua_assert(lo
+ r4
<= p
&& p
<= up
- r4
);
341 ** Quicksort algorithm (recursive function)
343 static void auxsort(lua_State
*L
, IdxT lo
, IdxT up
,
345 while (lo
< up
) { /* loop for tail recursion */
346 IdxT p
; /* Pivot index */
347 IdxT n
; /* to be used later */
348 /* sort elements 'lo', 'p', and 'up' */
351 if (sort_comp(L
, -1, -2)) /* a[up] < a[lo]? */
352 set2(L
, lo
, up
); /* swap a[lo] - a[up] */
354 lua_pop(L
, 2); /* remove both values */
355 if (up
- lo
== 1) /* only 2 elements? */
356 return; /* already sorted */
357 if (up
- lo
< RANLIMIT
|| rnd
== 0) /* small interval or no randomize? */
358 p
= (lo
+ up
) / 2; /* middle element is a good pivot */
359 else /* for larger intervals, it is worth a random pivot */
360 p
= choosePivot(lo
, up
, rnd
);
363 if (sort_comp(L
, -2, -1)) /* a[p] < a[lo]? */
364 set2(L
, p
, lo
); /* swap a[p] - a[lo] */
366 lua_pop(L
, 1); /* remove a[lo] */
368 if (sort_comp(L
, -1, -2)) /* a[up] < a[p]? */
369 set2(L
, p
, up
); /* swap a[up] - a[p] */
373 if (up
- lo
== 2) /* only 3 elements? */
374 return; /* already sorted */
375 lua_geti(L
, 1, p
); /* get middle element (Pivot) */
376 lua_pushvalue(L
, -1); /* push Pivot */
377 lua_geti(L
, 1, up
- 1); /* push a[up - 1] */
378 set2(L
, p
, up
- 1); /* swap Pivot (a[p]) with a[up - 1] */
379 p
= partition(L
, lo
, up
);
380 /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
381 if (p
- lo
< up
- p
) { /* lower interval is smaller? */
382 auxsort(L
, lo
, p
- 1, rnd
); /* call recursively for lower interval */
383 n
= p
- lo
; /* size of smaller interval */
384 lo
= p
+ 1; /* tail call for [p + 1 .. up] (upper interval) */
386 auxsort(L
, p
+ 1, up
, rnd
); /* call recursively for upper interval */
387 n
= up
- p
; /* size of smaller interval */
388 up
= p
- 1; /* tail call for [lo .. p - 1] (lower interval) */
390 if ((up
- lo
) / 128 > n
) /* partition too imbalanced? */
391 rnd
= l_randomizePivot(); /* try a new randomization */
392 } /* tail call auxsort(L, lo, up, rnd) */
396 static int sort(lua_State
*L
) {
397 lua_Integer n
= aux_getn(L
, 1, TAB_RW
);
398 if (n
> 1) { /* non-trivial interval? */
399 luaL_argcheck(L
, n
< INT_MAX
, 1, "array too big");
400 if (!lua_isnoneornil(L
, 2)) /* is there a 2nd argument? */
401 luaL_checktype(L
, 2, LUA_TFUNCTION
); /* must be a function */
402 lua_settop(L
, 2); /* make sure there are two arguments */
403 auxsort(L
, 1, (IdxT
)n
, 0);
408 /* }====================================================== */
411 static const luaL_Reg tab_funcs
[] = {
423 LUAMOD_API
int luaopen_table(lua_State
*L
) {
424 luaL_newlib(L
, tab_funcs
);