lbaselib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /*
  2. ** $Id: lbaselib.c,v 1.1 2000/09/05 19:33:56 roberto Exp roberto $
  3. ** Basic library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "lua.h"
  11. #include "lauxlib.h"
  12. #include "lualib.h"
  13. /*
  14. ** If your system does not support `stderr', redefine this function, or
  15. ** redefine _ERRORMESSAGE so that it won't need _ALERT.
  16. */
  17. static int luaB__ALERT (lua_State *L) {
  18. fputs(luaL_check_string(L, 1), stderr);
  19. return 0;
  20. }
  21. /*
  22. ** Basic implementation of _ERRORMESSAGE.
  23. ** The library `liolib' redefines _ERRORMESSAGE for better error information.
  24. */
  25. static int luaB__ERRORMESSAGE (lua_State *L) {
  26. lua_settop(L, 1);
  27. lua_getglobals(L);
  28. lua_pushstring(L, LUA_ALERT);
  29. lua_rawget(L, -2);
  30. if (lua_isfunction(L, -1)) { /* avoid error loop if _ALERT is not defined */
  31. luaL_checktype(L, 1, "string");
  32. lua_pushvalue(L, -1); /* function to be called */
  33. lua_pushstring(L, "error: ");
  34. lua_pushvalue(L, 1);
  35. lua_pushstring(L, "\n");
  36. lua_concat(L, 3);
  37. lua_call(L, 1, 0);
  38. }
  39. return 0;
  40. }
  41. /*
  42. ** If your system does not support `stdout', you can just remove this function.
  43. ** If you need, you can define your own `print' function, following this
  44. ** model but changing `fputs' to put the strings at a proper place
  45. ** (a console window or a log file, for instance).
  46. */
  47. static int luaB_print (lua_State *L) {
  48. int n = lua_gettop(L); /* number of arguments */
  49. int i;
  50. lua_getglobal(L, "tostring");
  51. for (i=1; i<=n; i++) {
  52. const char *s;
  53. lua_pushvalue(L, -1); /* function to be called */
  54. lua_pushvalue(L, i); /* value to print */
  55. if (lua_call(L, 1, 1) != 0)
  56. lua_error(L, NULL);
  57. s = lua_tostring(L, -1); /* get result */
  58. if (s == NULL)
  59. lua_error(L, "`tostring' must return a string to `print'");
  60. if (i>1) fputs("\t", stdout);
  61. fputs(s, stdout);
  62. lua_pop(L, 1); /* pop result */
  63. }
  64. fputs("\n", stdout);
  65. return 0;
  66. }
  67. static int luaB_tonumber (lua_State *L) {
  68. int base = luaL_opt_int(L, 2, 10);
  69. if (base == 10) { /* standard conversion */
  70. luaL_checktype(L, 1, "any");
  71. if (lua_isnumber(L, 1)) {
  72. lua_pushnumber(L, lua_tonumber(L, 1));
  73. return 1;
  74. }
  75. }
  76. else {
  77. const char *s1 = luaL_check_string(L, 1);
  78. char *s2;
  79. unsigned long n;
  80. luaL_arg_check(L, 2 <= base && base <= 36, 2, "base out of range");
  81. n = strtoul(s1, &s2, base);
  82. if (s1 != s2) { /* at least one valid digit? */
  83. while (isspace((unsigned char)*s2)) s2++; /* skip trailing spaces */
  84. if (*s2 == '\0') { /* no invalid trailing characters? */
  85. lua_pushnumber(L, n);
  86. return 1;
  87. }
  88. }
  89. }
  90. lua_pushnil(L); /* else not a number */
  91. return 1;
  92. }
  93. static int luaB_error (lua_State *L) {
  94. lua_error(L, luaL_opt_string(L, 1, NULL));
  95. return 0; /* to avoid warnings */
  96. }
  97. static int luaB_setglobal (lua_State *L) {
  98. luaL_checktype(L, 2, "any");
  99. lua_setglobal(L, luaL_check_string(L, 1));
  100. return 0;
  101. }
  102. static int luaB_getglobal (lua_State *L) {
  103. lua_getglobal(L, luaL_check_string(L, 1));
  104. return 1;
  105. }
  106. static int luaB_tag (lua_State *L) {
  107. luaL_checktype(L, 1, "any");
  108. lua_pushnumber(L, lua_tag(L, 1));
  109. return 1;
  110. }
  111. static int luaB_settag (lua_State *L) {
  112. luaL_checktype(L, 1, "table");
  113. lua_pushvalue(L, 1); /* push table */
  114. lua_settag(L, luaL_check_int(L, 2));
  115. lua_pop(L, 1); /* remove second argument */
  116. return 1; /* return first argument */
  117. }
  118. static int luaB_newtag (lua_State *L) {
  119. lua_pushnumber(L, lua_newtag(L));
  120. return 1;
  121. }
  122. static int luaB_copytagmethods (lua_State *L) {
  123. lua_pushnumber(L, lua_copytagmethods(L, luaL_check_int(L, 1),
  124. luaL_check_int(L, 2)));
  125. return 1;
  126. }
  127. static int luaB_globals (lua_State *L) {
  128. lua_getglobals(L); /* value to be returned */
  129. if (!lua_isnull(L, 1)) {
  130. luaL_checktype(L, 1, "table");
  131. lua_pushvalue(L, 1); /* new table of globals */
  132. lua_setglobals(L);
  133. }
  134. return 1;
  135. }
  136. static int luaB_rawget (lua_State *L) {
  137. luaL_checktype(L, 1, "table");
  138. luaL_checktype(L, 2, "any");
  139. lua_rawget(L, -2);
  140. return 1;
  141. }
  142. static int luaB_rawset (lua_State *L) {
  143. luaL_checktype(L, 1, "table");
  144. luaL_checktype(L, 2, "any");
  145. luaL_checktype(L, 3, "any");
  146. lua_rawset(L, -3);
  147. return 1;
  148. }
  149. static int luaB_settagmethod (lua_State *L) {
  150. int tag = (int)luaL_check_int(L, 1);
  151. const char *event = luaL_check_string(L, 2);
  152. luaL_arg_check(L, lua_isfunction(L, 3) || lua_isnil(L, 3), 3,
  153. "function or nil expected");
  154. lua_pushnil(L); /* to get its tag */
  155. if (strcmp(event, "gc") == 0 && tag != lua_tag(L, -1))
  156. lua_error(L, "deprecated use: cannot set the `gc' tag method from Lua");
  157. lua_pop(L, 1); /* remove the nil */
  158. lua_settagmethod(L, tag, event);
  159. return 1;
  160. }
  161. static int luaB_gettagmethod (lua_State *L) {
  162. lua_gettagmethod(L, luaL_check_int(L, 1), luaL_check_string(L, 2));
  163. return 1;
  164. }
  165. static int luaB_collectgarbage (lua_State *L) {
  166. lua_pushnumber(L, lua_collectgarbage(L, luaL_opt_int(L, 1, 0)));
  167. return 1;
  168. }
  169. static int luaB_type (lua_State *L) {
  170. luaL_checktype(L, 1, "any");
  171. lua_pushstring(L, lua_type(L, 1));
  172. return 1;
  173. }
  174. static int luaB_next (lua_State *L) {
  175. luaL_checktype(L, 1, "table");
  176. lua_settop(L, 2); /* create a 2nd argument if there isn't one */
  177. if (lua_next(L, 1))
  178. return 2;
  179. else {
  180. lua_pushnil(L);
  181. return 1;
  182. }
  183. }
  184. static int passresults (lua_State *L, int status, int oldtop) {
  185. static const char *const errornames[] =
  186. {"OK", "RUN-TIME ERROR", "FILE ERROR", "SYNTAX ERROR", "MEMORY ERROR"};
  187. if (status == 0) {
  188. int nresults = lua_gettop(L) - oldtop;
  189. if (nresults > 0)
  190. return nresults; /* results are already on the stack */
  191. else {
  192. lua_pushuserdata(L, NULL); /* at least one result to signal no errors */
  193. return 1;
  194. }
  195. }
  196. else { /* error */
  197. lua_pushnil(L);
  198. lua_pushstring(L, errornames[status]); /* error code */
  199. return 2;
  200. }
  201. }
  202. static int luaB_dostring (lua_State *L) {
  203. int oldtop = lua_gettop(L);
  204. size_t l;
  205. const char *s = luaL_check_lstr(L, 1, &l);
  206. if (*s == '\27') /* binary files start with ESC... */
  207. lua_error(L, "`dostring' cannot run pre-compiled code");
  208. return passresults(L, lua_dobuffer(L, s, l, luaL_opt_string(L, 2, s)), oldtop);
  209. }
  210. static int luaB_dofile (lua_State *L) {
  211. int oldtop = lua_gettop(L);
  212. const char *fname = luaL_opt_string(L, 1, NULL);
  213. return passresults(L, lua_dofile(L, fname), oldtop);
  214. }
  215. static int luaB_call (lua_State *L) {
  216. int oldtop;
  217. const char *options = luaL_opt_string(L, 3, "");
  218. int err = 0; /* index of old error method */
  219. int i, status;
  220. int n;
  221. luaL_checktype(L, 2, "table");
  222. n = lua_getn(L, 2);
  223. if (!lua_isnull(L, 4)) { /* set new error method */
  224. lua_getglobal(L, LUA_ERRORMESSAGE);
  225. err = lua_gettop(L); /* get index */
  226. lua_pushvalue(L, 4);
  227. lua_setglobal(L, LUA_ERRORMESSAGE);
  228. }
  229. oldtop = lua_gettop(L); /* top before function-call preparation */
  230. /* push function */
  231. lua_pushvalue(L, 1);
  232. luaL_checkstack(L, n, "too many arguments");
  233. for (i=0; i<n; i++) /* push arg[1...n] */
  234. lua_rawgeti(L, 2, i+1);
  235. status = lua_call(L, n, LUA_MULTRET);
  236. if (err != 0) { /* restore old error method */
  237. lua_pushvalue(L, err);
  238. lua_setglobal(L, LUA_ERRORMESSAGE);
  239. }
  240. if (status != 0) { /* error in call? */
  241. if (strchr(options, 'x'))
  242. lua_pushnil(L); /* return nil to signal the error */
  243. else
  244. lua_error(L, NULL); /* propagate error without additional messages */
  245. return 1;
  246. }
  247. if (strchr(options, 'p')) /* pack results? */
  248. lua_error(L, "deprecated option `p' in `call'");
  249. return lua_gettop(L) - oldtop; /* results are already on the stack */
  250. }
  251. static int luaB_tostring (lua_State *L) {
  252. char buff[64];
  253. switch (lua_type(L, 1)[2]) {
  254. case 'm': /* nuMber */
  255. lua_pushstring(L, lua_tostring(L, 1));
  256. return 1;
  257. case 'r': /* stRing */
  258. lua_pushvalue(L, 1);
  259. return 1;
  260. case 'b': /* taBle */
  261. sprintf(buff, "table: %p", lua_topointer(L, 1));
  262. break;
  263. case 'n': /* fuNction */
  264. sprintf(buff, "function: %p", lua_topointer(L, 1));
  265. break;
  266. case 'e': /* usErdata */
  267. sprintf(buff, "userdata(%d): %p", lua_tag(L, 1), lua_touserdata(L, 1));
  268. break;
  269. case 'l': /* niL */
  270. lua_pushstring(L, "nil");
  271. return 1;
  272. default:
  273. luaL_argerror(L, 1, "value expected");
  274. }
  275. lua_pushstring(L, buff);
  276. return 1;
  277. }
  278. static int luaB_foreachi (lua_State *L) {
  279. int n, i;
  280. luaL_checktype(L, 1, "table");
  281. luaL_checktype(L, 2, "function");
  282. n = lua_getn(L, 1);
  283. for (i=1; i<=n; i++) {
  284. lua_pushvalue(L, 2); /* function */
  285. lua_pushnumber(L, i); /* 1st argument */
  286. lua_rawgeti(L, 1, i); /* 2nd argument */
  287. if (lua_call(L, 2, 1) != 0)
  288. lua_error(L, NULL);
  289. if (!lua_isnil(L, -1))
  290. return 1;
  291. lua_pop(L, 1); /* remove nil result */
  292. }
  293. return 0;
  294. }
  295. static int luaB_foreach (lua_State *L) {
  296. luaL_checktype(L, 1, "table");
  297. luaL_checktype(L, 2, "function");
  298. lua_pushnil(L); /* first index */
  299. for (;;) {
  300. if (lua_next(L, 1) == 0)
  301. return 0;
  302. lua_pushvalue(L, 2); /* function */
  303. lua_pushvalue(L, -3); /* key */
  304. lua_pushvalue(L, -3); /* value */
  305. if (lua_call(L, 2, 1) != 0) lua_error(L, NULL);
  306. if (!lua_isnil(L, -1))
  307. return 1;
  308. lua_pop(L, 2); /* remove value and result */
  309. }
  310. }
  311. static int luaB_assert (lua_State *L) {
  312. luaL_checktype(L, 1, "any");
  313. if (lua_isnil(L, 1))
  314. luaL_verror(L, "assertion failed! %.90s", luaL_opt_string(L, 2, ""));
  315. return 0;
  316. }
  317. static int luaB_getn (lua_State *L) {
  318. luaL_checktype(L, 1, "table");
  319. lua_pushnumber(L, lua_getn(L, 1));
  320. return 1;
  321. }
  322. static int luaB_tinsert (lua_State *L) {
  323. int v = lua_gettop(L); /* last argument: to be inserted */
  324. int n, pos;
  325. luaL_checktype(L, 1, "table");
  326. n = lua_getn(L, 1);
  327. if (v == 2) /* called with only 2 arguments */
  328. pos = n+1;
  329. else
  330. pos = luaL_check_int(L, 2); /* 2nd argument is the position */
  331. lua_pushstring(L, "n");
  332. lua_pushnumber(L, n+1);
  333. lua_rawset(L, 1); /* t.n = n+1 */
  334. for (; n>=pos; n--) {
  335. lua_rawgeti(L, 1, n);
  336. lua_rawseti(L, 1, n+1); /* t[n+1] = t[n] */
  337. }
  338. lua_pushvalue(L, v);
  339. lua_rawseti(L, 1, pos); /* t[pos] = v */
  340. return 0;
  341. }
  342. static int luaB_tremove (lua_State *L) {
  343. int pos, n;
  344. luaL_checktype(L, 1, "table");
  345. n = lua_getn(L, 1);
  346. pos = luaL_opt_int(L, 2, n);
  347. if (n <= 0) return 0; /* table is "empty" */
  348. lua_rawgeti(L, 1, pos); /* result = t[pos] */
  349. for ( ;pos<n; pos++) {
  350. lua_rawgeti(L, 1, pos+1);
  351. lua_rawseti(L, 1, pos); /* a[pos] = a[pos+1] */
  352. }
  353. lua_pushstring(L, "n");
  354. lua_pushnumber(L, n-1);
  355. lua_rawset(L, 1); /* t.n = n-1 */
  356. lua_pushnil(L);
  357. lua_rawseti(L, 1, n); /* t[n] = nil */
  358. return 1;
  359. }
  360. /*
  361. ** {======================================================
  362. ** Quicksort
  363. ** (based on `Algorithms in MODULA-3', Robert Sedgewick;
  364. ** Addison-Wesley, 1993.)
  365. */
  366. static void swap (lua_State *L, int i, int j) {
  367. lua_rawgeti(L, 1, i);
  368. lua_rawgeti(L, 1, j);
  369. lua_rawseti(L, 1, i);
  370. lua_rawseti(L, 1, j);
  371. }
  372. static int sort_comp (lua_State *L, int n, int r) {
  373. /* WARNING: the caller (auxsort) must ensure stack space */
  374. int res;
  375. if (!lua_isnil(L, 2)) { /* function? */
  376. lua_pushvalue(L, 2);
  377. if (r) {
  378. lua_rawgeti(L, 1, n); /* a[n] */
  379. lua_pushvalue(L, -3); /* pivot */
  380. }
  381. else {
  382. lua_pushvalue(L, -2); /* pivot */
  383. lua_rawgeti(L, 1, n); /* a[n] */
  384. }
  385. if (lua_call(L, 2, 1) != 0) lua_error(L, NULL);
  386. res = !lua_isnil(L, -1);
  387. }
  388. else { /* a < b? */
  389. lua_rawgeti(L, 1, n); /* a[n] */
  390. if (r)
  391. res = lua_lessthan(L, -1, -2);
  392. else
  393. res = lua_lessthan(L, -2, -1);
  394. }
  395. lua_pop(L, 1);
  396. return res;
  397. }
  398. static void auxsort (lua_State *L, int l, int u) {
  399. while (l < u) { /* for tail recursion */
  400. int i, j;
  401. luaL_checkstack(L, 4, "array too large");
  402. /* sort elements a[l], a[(l+u)/2] and a[u] */
  403. lua_rawgeti(L, 1, u);
  404. if (sort_comp(L, l, 0)) /* a[u] < a[l]? */
  405. swap(L, l, u);
  406. lua_pop(L, 1);
  407. if (u-l == 1) break; /* only 2 elements */
  408. i = (l+u)/2;
  409. lua_rawgeti(L, 1, i); /* Pivot = a[i] */
  410. if (sort_comp(L, l, 0)) /* a[i]<a[l]? */
  411. swap(L, l, i);
  412. else {
  413. if (sort_comp(L, u, 1)) /* a[u]<a[i]? */
  414. swap(L, i, u);
  415. }
  416. lua_pop(L, 1); /* pop old a[i] */
  417. if (u-l == 2) break; /* only 3 elements */
  418. lua_rawgeti(L, 1, i); /* Pivot */
  419. swap(L, i, u-1); /* put median element as pivot (a[u-1]) */
  420. /* a[l] <= P == a[u-1] <= a[u], only needs to sort from l+1 to u-2 */
  421. i = l; j = u-1;
  422. for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */
  423. /* repeat i++ until a[i] >= P */
  424. while (sort_comp(L, ++i, 1))
  425. if (i>u) lua_error(L, "invalid order function for sorting");
  426. /* repeat j-- until a[j] <= P */
  427. while (sort_comp(L, --j, 0))
  428. if (j<l) lua_error(L, "invalid order function for sorting");
  429. if (j<i) break;
  430. swap(L, i, j);
  431. }
  432. swap(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */
  433. /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
  434. /* adjust so that smaller "half" is in [j..i] and larger one in [l..u] */
  435. if (i-l < u-i) {
  436. j=l; i=i-1; l=i+2;
  437. }
  438. else {
  439. j=i+1; i=u; u=j-2;
  440. }
  441. lua_pop(L, 1); /* remove pivot from stack */
  442. auxsort(L, j, i); /* call recursively the smaller one */
  443. } /* repeat the routine for the larger one */
  444. }
  445. static int luaB_sort (lua_State *L) {
  446. int n;
  447. luaL_checktype(L, 1, "table");
  448. n = lua_getn(L, 1);
  449. if (!lua_isnull(L, 2)) /* is there a 2nd argument? */
  450. luaL_checktype(L, 2, "function");
  451. lua_settop(L, 2); /* make sure there is two arguments */
  452. auxsort(L, 1, n);
  453. return 0;
  454. }
  455. /* }====================================================== */
  456. /*
  457. ** {======================================================
  458. ** Deprecated functions to manipulate global environment.
  459. ** =======================================================
  460. */
  461. /*
  462. ** gives an explicit error in any attempt to call a deprecated function
  463. */
  464. static int deprecated_func (lua_State *L) {
  465. luaL_verror(L, "function `%.20s' is deprecated", luaL_check_string(L, -1));
  466. return 0; /* to avoid warnings */
  467. }
  468. #define num_deprecated 4
  469. static const char *const deprecated_names [num_deprecated] = {
  470. "foreachvar", "nextvar", "rawgetglobal", "rawsetglobal"
  471. };
  472. static void deprecated_funcs (lua_State *L) {
  473. int i;
  474. for (i=0; i<num_deprecated; i++) {
  475. lua_pushstring(L, deprecated_names[i]);
  476. lua_pushcclosure(L, deprecated_func, 1);
  477. lua_setglobal(L, deprecated_names[i]);
  478. }
  479. }
  480. /* }====================================================== */
  481. static const struct luaL_reg base_funcs[] = {
  482. {LUA_ALERT, luaB__ALERT},
  483. {LUA_ERRORMESSAGE, luaB__ERRORMESSAGE},
  484. {"call", luaB_call},
  485. {"collectgarbage", luaB_collectgarbage},
  486. {"copytagmethods", luaB_copytagmethods},
  487. {"dofile", luaB_dofile},
  488. {"dostring", luaB_dostring},
  489. {"error", luaB_error},
  490. {"foreach", luaB_foreach},
  491. {"foreachi", luaB_foreachi},
  492. {"getglobal", luaB_getglobal},
  493. {"gettagmethod", luaB_gettagmethod},
  494. {"globals", luaB_globals},
  495. {"newtag", luaB_newtag},
  496. {"next", luaB_next},
  497. {"print", luaB_print},
  498. {"rawget", luaB_rawget},
  499. {"rawset", luaB_rawset},
  500. {"rawgettable", luaB_rawget}, /* for compatibility */
  501. {"rawsettable", luaB_rawset}, /* for compatibility */
  502. {"setglobal", luaB_setglobal},
  503. {"settag", luaB_settag},
  504. {"settagmethod", luaB_settagmethod},
  505. {"tag", luaB_tag},
  506. {"tonumber", luaB_tonumber},
  507. {"tostring", luaB_tostring},
  508. {"type", luaB_type},
  509. {"assert", luaB_assert},
  510. {"getn", luaB_getn},
  511. {"sort", luaB_sort},
  512. {"tinsert", luaB_tinsert},
  513. {"tremove", luaB_tremove}
  514. };
  515. void lua_baselibopen (lua_State *L) {
  516. luaL_openl(L, base_funcs);
  517. lua_pushstring(L, LUA_VERSION);
  518. lua_setglobal(L, "_VERSION");
  519. deprecated_funcs(L);
  520. }