ltablib.c
Go to the documentation of this file.
1 /*
2 ** $Id: ltablib.c $
3 ** Library for Table Manipulation
4 ** See Copyright Notice in lua.h
5 */
6 
7 #define ltablib_c
8 #define LUA_LIB
9 
10 #include "lprefix.h"
11 
12 
13 #include <limits.h>
14 #include <stddef.h>
15 #include <string.h>
16 
17 #include "lua.h"
18 
19 #include "lauxlib.h"
20 #include "lualib.h"
21 
22 
23 /*
24 ** Operations that an object must define to mimic a table
25 ** (some functions only need some of them)
26 */
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 */
31 
32 
33 #define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n))
34 
35 
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);
39 }
40 
41 
42 /*
43 ** Check that 'arg' either is a table or can behave like one (that is,
44 ** has a metatable with the required metamethods)
45 */
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 */
54  }
55  else
56  luaL_checktype(L, arg, LUA_TTABLE); /* force an error */
57  }
58 }
59 
60 
61 static int tinsert (lua_State *L) {
62  lua_Integer e = aux_getn(L, 1, TAB_RW) + 1; /* first empty element */
63  lua_Integer pos; /* where to insert new element */
64  switch (lua_gettop(L)) {
65  case 2: { /* called with only 2 arguments */
66  pos = e; /* insert new element at the end */
67  break;
68  }
69  case 3: {
70  lua_Integer i;
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] */
78  }
79  break;
80  }
81  default: {
82  return luaL_error(L, "wrong number of arguments to 'insert'");
83  }
84  }
85  lua_seti(L, 1, pos); /* t[pos] = v */
86  return 0;
87 }
88 
89 
90 static int tremove (lua_State *L) {
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, 1,
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] */
101  }
102  lua_pushnil(L);
103  lua_seti(L, 1, pos); /* remove entry t[pos] */
104  return 1;
105 }
106 
107 
108 /*
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.
113 */
114 static int tmove (lua_State *L) {
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 */
122  lua_Integer n, i;
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);
132  }
133  }
134  else {
135  for (i = n - 1; i >= 0; i--) {
136  lua_geti(L, 1, f + i);
137  lua_seti(L, tt, t + i);
138  }
139  }
140  }
141  lua_pushvalue(L, tt); /* return destination table */
142  return 1;
143 }
144 
145 
146 static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
147  lua_geti(L, 1, i);
148  if (l_unlikely(!lua_isstring(L, -1)))
149  luaL_error(L, "invalid value (%s) at index %I in table for 'concat'",
150  luaL_typename(L, -1), i);
151  luaL_addvalue(b);
152 }
153 
154 
155 static int tconcat (lua_State *L) {
156  luaL_Buffer b;
157  lua_Integer last = aux_getn(L, 1, TAB_R);
158  size_t lsep;
159  const char *sep = luaL_optlstring(L, 2, "", &lsep);
160  lua_Integer i = luaL_optinteger(L, 3, 1);
161  last = luaL_optinteger(L, 4, last);
162  luaL_buffinit(L, &b);
163  for (; i < last; i++) {
164  addfield(L, &b, i);
165  luaL_addlstring(&b, sep, lsep);
166  }
167  if (i == last) /* add last value (if interval was not empty) */
168  addfield(L, &b, i);
169  luaL_pushresult(&b);
170  return 1;
171 }
172 
173 
174 /*
175 ** {======================================================
176 ** Pack/unpack
177 ** =======================================================
178 */
179 
180 static int tpack (lua_State *L) {
181  int i;
182  int n = lua_gettop(L); /* number of elements to pack */
183  lua_createtable(L, n, 1); /* create result table */
184  lua_insert(L, 1); /* put it at index 1 */
185  for (i = n; i >= 1; i--) /* assign elements */
186  lua_seti(L, 1, i);
187  lua_pushinteger(L, n);
188  lua_setfield(L, 1, "n"); /* t.n = number of elements */
189  return 1; /* return table */
190 }
191 
192 
193 static int tunpack (lua_State *L) {
194  lua_Unsigned n;
195  lua_Integer i = luaL_optinteger(L, 2, 1);
197  if (i > e) return 0; /* empty range */
198  n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */
199  if (l_unlikely(n >= (unsigned int)INT_MAX ||
200  !lua_checkstack(L, (int)(++n))))
201  return luaL_error(L, "too many results to unpack");
202  for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */
203  lua_geti(L, 1, i);
204  }
205  lua_geti(L, 1, e); /* push last element */
206  return (int)n;
207 }
208 
209 /* }====================================================== */
210 
211 
212 
213 /*
214 ** {======================================================
215 ** Quicksort
216 ** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
217 ** Addison-Wesley, 1993.)
218 ** =======================================================
219 */
220 
221 
222 /* type for array indices */
223 typedef unsigned int IdxT;
224 
225 
226 /*
227 ** Produce a "random" 'unsigned int' to randomize pivot choice. This
228 ** macro is used only when 'sort' detects a big imbalance in the result
229 ** of a partition. (If you don't want/need this "randomness", ~0 is a
230 ** good choice.)
231 */
232 #if !defined(l_randomizePivot) /* { */
233 
234 #include <time.h>
235 
236 /* size of 'e' measured in number of 'unsigned int's */
237 #define sof(e) (sizeof(e) / sizeof(unsigned int))
238 
239 /*
240 ** Use 'time' and 'clock' as sources of "randomness". Because we don't
241 ** know the types 'clock_t' and 'time_t', we cannot cast them to
242 ** anything without risking overflows. A safe way to use their values
243 ** is to copy them to an array of a known type and use the array values.
244 */
245 static unsigned int l_randomizePivot (void) {
246  clock_t c = clock();
247  time_t t = time(NULL);
248  unsigned int buff[sof(c) + sof(t)];
249  unsigned int i, rnd = 0;
250  memcpy(buff, &c, sof(c) * sizeof(unsigned int));
251  memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int));
252  for (i = 0; i < sof(buff); i++)
253  rnd += buff[i];
254  return rnd;
255 }
256 
257 #endif /* } */
258 
259 
260 /* arrays larger than 'RANLIMIT' may use randomized pivots */
261 #define RANLIMIT 100u
262 
263 
264 static void set2 (lua_State *L, IdxT i, IdxT j) {
265  lua_seti(L, 1, i);
266  lua_seti(L, 1, j);
267 }
268 
269 
270 /*
271 ** Return true iff value at stack index 'a' is less than the value at
272 ** index 'b' (according to the order of the sort).
273 */
274 static int sort_comp (lua_State *L, int a, int b) {
275  if (lua_isnil(L, 2)) /* no function? */
276  return lua_compare(L, a, b, LUA_OPLT); /* a < b */
277  else { /* function */
278  int res;
279  lua_pushvalue(L, 2); /* push function */
280  lua_pushvalue(L, a-1); /* -1 to compensate function */
281  lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */
282  lua_call(L, 2, 1); /* call function */
283  res = lua_toboolean(L, -1); /* get result */
284  lua_pop(L, 1); /* pop result */
285  return res;
286  }
287 }
288 
289 
290 /*
291 ** Does the partition: Pivot P is at the top of the stack.
292 ** precondition: a[lo] <= P == a[up-1] <= a[up],
293 ** so it only needs to do the partition from lo + 1 to up - 2.
294 ** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up]
295 ** returns 'i'.
296 */
297 static IdxT partition (lua_State *L, IdxT lo, IdxT up) {
298  IdxT i = lo; /* will be incremented before first use */
299  IdxT j = up - 1; /* will be decremented before first use */
300  /* loop invariant: a[lo .. i] <= P <= a[j .. up] */
301  for (;;) {
302  /* next loop: repeat ++i while a[i] < P */
303  while ((void)lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {
304  if (l_unlikely(i == up - 1)) /* a[i] < P but a[up - 1] == P ?? */
305  luaL_error(L, "invalid order function for sorting");
306  lua_pop(L, 1); /* remove a[i] */
307  }
308  /* after the loop, a[i] >= P and a[lo .. i - 1] < P */
309  /* next loop: repeat --j while P < a[j] */
310  while ((void)lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {
311  if (l_unlikely(j < i)) /* j < i but a[j] > P ?? */
312  luaL_error(L, "invalid order function for sorting");
313  lua_pop(L, 1); /* remove a[j] */
314  }
315  /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */
316  if (j < i) { /* no elements out of place? */
317  /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */
318  lua_pop(L, 1); /* pop a[j] */
319  /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */
320  set2(L, up - 1, i);
321  return i;
322  }
323  /* otherwise, swap a[i] - a[j] to restore invariant and repeat */
324  set2(L, i, j);
325  }
326 }
327 
328 
329 /*
330 ** Choose an element in the middle (2nd-3th quarters) of [lo,up]
331 ** "randomized" by 'rnd'
332 */
333 static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {
334  IdxT r4 = (up - lo) / 4; /* range/4 */
335  IdxT p = rnd % (r4 * 2) + (lo + r4);
336  lua_assert(lo + r4 <= p && p <= up - r4);
337  return p;
338 }
339 
340 
341 /*
342 ** Quicksort algorithm (recursive function)
343 */
344 static void auxsort (lua_State *L, IdxT lo, IdxT up,
345  unsigned int rnd) {
346  while (lo < up) { /* loop for tail recursion */
347  IdxT p; /* Pivot index */
348  IdxT n; /* to be used later */
349  /* sort elements 'lo', 'p', and 'up' */
350  lua_geti(L, 1, lo);
351  lua_geti(L, 1, up);
352  if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */
353  set2(L, lo, up); /* swap a[lo] - a[up] */
354  else
355  lua_pop(L, 2); /* remove both values */
356  if (up - lo == 1) /* only 2 elements? */
357  return; /* already sorted */
358  if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */
359  p = (lo + up)/2; /* middle element is a good pivot */
360  else /* for larger intervals, it is worth a random pivot */
361  p = choosePivot(lo, up, rnd);
362  lua_geti(L, 1, p);
363  lua_geti(L, 1, lo);
364  if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */
365  set2(L, p, lo); /* swap a[p] - a[lo] */
366  else {
367  lua_pop(L, 1); /* remove a[lo] */
368  lua_geti(L, 1, up);
369  if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */
370  set2(L, p, up); /* swap a[up] - a[p] */
371  else
372  lua_pop(L, 2);
373  }
374  if (up - lo == 2) /* only 3 elements? */
375  return; /* already sorted */
376  lua_geti(L, 1, p); /* get middle element (Pivot) */
377  lua_pushvalue(L, -1); /* push Pivot */
378  lua_geti(L, 1, up - 1); /* push a[up - 1] */
379  set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */
380  p = partition(L, lo, up);
381  /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */
382  if (p - lo < up - p) { /* lower interval is smaller? */
383  auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */
384  n = p - lo; /* size of smaller interval */
385  lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */
386  }
387  else {
388  auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */
389  n = up - p; /* size of smaller interval */
390  up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */
391  }
392  if ((up - lo) / 128 > n) /* partition too imbalanced? */
393  rnd = l_randomizePivot(); /* try a new randomization */
394  } /* tail call auxsort(L, lo, up, rnd) */
395 }
396 
397 
398 static int sort (lua_State *L) {
399  lua_Integer n = aux_getn(L, 1, TAB_RW);
400  if (n > 1) { /* non-trivial interval? */
401  luaL_argcheck(L, n < INT_MAX, 1, "array too big");
402  if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
403  luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */
404  lua_settop(L, 2); /* make sure there are two arguments */
405  auxsort(L, 1, (IdxT)n, 0);
406  }
407  return 0;
408 }
409 
410 /* }====================================================== */
411 
412 
413 static const luaL_Reg tab_funcs[] = {
414  {"concat", tconcat},
415  {"insert", tinsert},
416  {"pack", tpack},
417  {"unpack", tunpack},
418  {"remove", tremove},
419  {"move", tmove},
420  {"sort", sort},
421  {NULL, NULL}
422 };
423 
424 
427  return 1;
428 }
429 
tab_funcs
static const luaL_Reg tab_funcs[]
Definition: ltablib.c:413
TAB_R
#define TAB_R
Definition: ltablib.c:27
LUA_TFUNCTION
#define LUA_TFUNCTION
Definition: lua.h:71
sort_comp
static int sort_comp(lua_State *L, int a, int b)
Definition: ltablib.c:274
lua_assert
#define lua_assert(c)
Definition: lauxlib.h:170
lua_Unsigned
LUA_UNSIGNED lua_Unsigned
Definition: lua.h:97
lua_geti
LUA_API int lua_geti(lua_State *L, int idx, lua_Integer n)
Definition: lapi.c:689
IdxT
unsigned int IdxT
Definition: ltablib.c:223
TAB_W
#define TAB_W
Definition: ltablib.c:28
tmove
static int tmove(lua_State *L)
Definition: ltablib.c:114
luaL_Reg
Definition: lauxlib.h:38
l_randomizePivot
static unsigned int l_randomizePivot(void)
Definition: ltablib.c:245
lua_checkstack
LUA_API int lua_checkstack(lua_State *L, int n)
Definition: lapi.c:99
tpack
static int tpack(lua_State *L)
Definition: ltablib.c:180
luaL_buffinit
LUALIB_API void luaL_buffinit(lua_State *L, luaL_Buffer *B)
Definition: lauxlib.c:629
LUA_TTABLE
#define LUA_TTABLE
Definition: lua.h:70
checkfield
static int checkfield(lua_State *L, const char *key, int n)
Definition: ltablib.c:36
lua_pushinteger
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
Definition: lapi.c:507
time.h
lua_pop
#define lua_pop(L, n)
Definition: lua.h:365
luaL_typename
#define luaL_typename(L, i)
Definition: lauxlib.h:142
set2
static void set2(lua_State *L, IdxT i, IdxT j)
Definition: ltablib.c:264
arg
auto arg(const Char *name, const T &arg) -> detail::named_arg< Char, T >
Definition: core.h:1875
lua_isnoneornil
#define lua_isnoneornil(L, n)
Definition: lua.h:380
luaL_addlstring
LUALIB_API void luaL_addlstring(luaL_Buffer *B, const char *s, size_t l)
Definition: lauxlib.c:579
TAB_RW
#define TAB_RW
Definition: ltablib.c:30
lua_isstring
LUA_API int lua_isstring(lua_State *L, int idx)
Definition: lapi.c:310
lua_type
LUA_API int lua_type(lua_State *L, int idx)
Definition: lapi.c:278
lua_pushstring
const LUA_API char * lua_pushstring(lua_State *L, const char *s)
Definition: lapi.c:532
luaopen_table
LUAMOD_API int luaopen_table(lua_State *L)
Definition: ltablib.c:425
luaL_pushresult
LUALIB_API void luaL_pushresult(luaL_Buffer *B)
Definition: lauxlib.c:593
f
f
luaL_optlstring
const LUALIB_API char * luaL_optlstring(lua_State *L, int arg, const char *def, size_t *len)
Definition: lauxlib.c:409
choosePivot
static IdxT choosePivot(IdxT lo, IdxT up, unsigned int rnd)
Definition: ltablib.c:333
tremove
static int tremove(lua_State *L)
Definition: ltablib.c:90
checktab
static void checktab(lua_State *L, int arg, int what)
Definition: ltablib.c:46
lua.h
LUA_OPEQ
#define LUA_OPEQ
Definition: lua.h:222
nonstd::span_lite::size
span_constexpr std::size_t size(span< T, Extent > const &spn)
Definition: span.hpp:1554
tconcat
static int tconcat(lua_State *L)
Definition: ltablib.c:155
lua_insert
#define lua_insert(L, idx)
Definition: lua.h:390
lua_rawget
LUA_API int lua_rawget(lua_State *L, int idx)
Definition: lapi.c:726
lua_setfield
LUA_API void lua_setfield(lua_State *L, int idx, const char *k)
Definition: lapi.c:865
lprefix.h
lua_State
Definition: lstate.h:304
mqtt_test.time
float time
Definition: mqtt_test.py:17
LUA_OPLT
#define LUA_OPLT
Definition: lua.h:223
luaL_opt
#define luaL_opt(L, f, n, d)
Definition: lauxlib.h:152
luaL_argcheck
#define luaL_argcheck(L, cond, arg, extramsg)
Definition: lauxlib.h:133
tinsert
static int tinsert(lua_State *L)
Definition: ltablib.c:61
lua_gettop
LUA_API int lua_gettop(lua_State *L)
Definition: lapi.c:169
lua_Integer
LUA_INTEGER lua_Integer
Definition: lua.h:94
lua_isnil
#define lua_isnil(L, n)
Definition: lua.h:376
lua_settop
LUA_API void lua_settop(lua_State *L, int idx)
Definition: lapi.c:174
lauxlib.h
lualib.h
sort
static int sort(lua_State *L)
Definition: ltablib.c:398
lua_pushvalue
LUA_API void lua_pushvalue(lua_State *L, int idx)
Definition: lapi.c:264
luaL_len
LUALIB_API lua_Integer luaL_len(lua_State *L, int idx)
Definition: lauxlib.c:871
luaL_checktype
LUALIB_API void luaL_checktype(lua_State *L, int arg, int t)
Definition: lauxlib.c:390
lua_getmetatable
LUA_API int lua_getmetatable(lua_State *L, int objindex)
Definition: lapi.c:769
lua_call
#define lua_call(L, n, r)
Definition: lua.h:283
tunpack
static int tunpack(lua_State *L)
Definition: ltablib.c:193
LUA_TNIL
#define LUA_TNIL
Definition: lua.h:65
LUAMOD_API
#define LUAMOD_API
Definition: luaconf.h:291
luaL_Buffer
Definition: lauxlib.h:183
aux_getn
#define aux_getn(L, n, w)
Definition: ltablib.c:33
RANLIMIT
#define RANLIMIT
Definition: ltablib.c:261
luaL_optinteger
LUALIB_API lua_Integer luaL_optinteger(lua_State *L, int arg, lua_Integer def)
Definition: lauxlib.c:452
luaL_newlib
#define luaL_newlib(L, l)
Definition: lauxlib.h:130
lua_seti
LUA_API void lua_seti(lua_State *L, int idx, lua_Integer n)
Definition: lapi.c:871
luaL_error
LUALIB_API int luaL_error(lua_State *L, const char *fmt,...)
Definition: lauxlib.c:234
sof
#define sof(e)
Definition: ltablib.c:237
luaL_checkinteger
LUALIB_API lua_Integer luaL_checkinteger(lua_State *L, int arg)
Definition: lauxlib.c:442
lua_pushnil
LUA_API void lua_pushnil(lua_State *L)
Definition: lapi.c:491
lua_toboolean
LUA_API int lua_toboolean(lua_State *L, int idx)
Definition: lapi.c:393
partition
static IdxT partition(lua_State *L, IdxT lo, IdxT up)
Definition: ltablib.c:297
auxsort
static void auxsort(lua_State *L, IdxT lo, IdxT up, unsigned int rnd)
Definition: ltablib.c:344
TAB_L
#define TAB_L
Definition: ltablib.c:29
luaL_addvalue
LUALIB_API void luaL_addvalue(luaL_Buffer *B)
Definition: lauxlib.c:618
lua_compare
LUA_API int lua_compare(lua_State *L, int index1, int index2, int op)
Definition: lapi.c:345
lua_createtable
LUA_API void lua_createtable(lua_State *L, int narray, int nrec)
Definition: lapi.c:756
addfield
static void addfield(lua_State *L, luaL_Buffer *b, lua_Integer i)
Definition: ltablib.c:146


plotjuggler
Author(s): Davide Faconti
autogenerated on Mon Nov 11 2024 03:23:45