lbaselib.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. /*
  2. ** $Id: lbaselib.c,v 1.60 2002/03/20 12:54:08 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 "luadebug.h"
  13. #include "lualib.h"
  14. /*
  15. ** If your system does not support `stderr', redefine this function, or
  16. ** redefine _ERRORMESSAGE so that it won't need _ALERT.
  17. */
  18. static int luaB__ALERT (lua_State *L) {
  19. fputs(luaL_check_string(L, 1), stderr);
  20. return 0;
  21. }
  22. /*
  23. ** Basic implementation of _ERRORMESSAGE.
  24. ** The library `liolib' redefines _ERRORMESSAGE for better error information.
  25. */
  26. static int luaB__ERRORMESSAGE (lua_State *L) {
  27. luaL_check_type(L, 1, LUA_TSTRING);
  28. lua_getglobal(L, LUA_ALERT);
  29. if (lua_isfunction(L, -1)) { /* avoid error loop if _ALERT is not defined */
  30. lua_Debug ar;
  31. lua_pushliteral(L, "error: ");
  32. lua_pushvalue(L, 1);
  33. if (lua_getstack(L, 1, &ar)) {
  34. lua_getinfo(L, "Sl", &ar);
  35. if (ar.source && ar.currentline > 0) {
  36. char buff[100];
  37. sprintf(buff, "\n <%.70s: line %d>", ar.short_src, ar.currentline);
  38. lua_pushstring(L, buff);
  39. lua_concat(L, 2);
  40. }
  41. }
  42. lua_pushliteral(L, "\n");
  43. lua_concat(L, 3);
  44. lua_rawcall(L, 1, 0);
  45. }
  46. return 0;
  47. }
  48. /*
  49. ** If your system does not support `stdout', you can just remove this function.
  50. ** If you need, you can define your own `print' function, following this
  51. ** model but changing `fputs' to put the strings at a proper place
  52. ** (a console window or a log file, for instance).
  53. */
  54. static int luaB_print (lua_State *L) {
  55. int n = lua_gettop(L); /* number of arguments */
  56. int i;
  57. lua_getglobal(L, "tostring");
  58. for (i=1; i<=n; i++) {
  59. const char *s;
  60. lua_pushvalue(L, -1); /* function to be called */
  61. lua_pushvalue(L, i); /* value to print */
  62. lua_rawcall(L, 1, 1);
  63. s = lua_tostring(L, -1); /* get result */
  64. if (s == NULL)
  65. lua_error(L, "`tostring' must return a string to `print'");
  66. if (i>1) fputs("\t", stdout);
  67. fputs(s, stdout);
  68. lua_pop(L, 1); /* pop result */
  69. }
  70. fputs("\n", stdout);
  71. return 0;
  72. }
  73. static int luaB_tonumber (lua_State *L) {
  74. int base = luaL_opt_int(L, 2, 10);
  75. if (base == 10) { /* standard conversion */
  76. luaL_check_any(L, 1);
  77. if (lua_isnumber(L, 1)) {
  78. lua_pushnumber(L, lua_tonumber(L, 1));
  79. return 1;
  80. }
  81. }
  82. else {
  83. const char *s1 = luaL_check_string(L, 1);
  84. char *s2;
  85. unsigned long n;
  86. luaL_arg_check(L, 2 <= base && base <= 36, 2, "base out of range");
  87. n = strtoul(s1, &s2, base);
  88. if (s1 != s2) { /* at least one valid digit? */
  89. while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */
  90. if (*s2 == '\0') { /* no invalid trailing characters? */
  91. lua_pushnumber(L, n);
  92. return 1;
  93. }
  94. }
  95. }
  96. lua_pushnil(L); /* else not a number */
  97. return 1;
  98. }
  99. static int luaB_error (lua_State *L) {
  100. lua_error(L, luaL_opt_string(L, 1, NULL));
  101. return 0; /* to avoid warnings */
  102. }
  103. static int luaB_metatable (lua_State *L) {
  104. luaL_check_any(L, 1);
  105. if (lua_isnone(L, 2)) {
  106. if (lua_getmetatable(L, 1)) {
  107. lua_pushliteral(L, "__metatable");
  108. lua_rawget(L, -2);
  109. if (lua_isnil(L, -1))
  110. lua_pop(L, 1);
  111. }
  112. }
  113. else {
  114. int t = lua_type(L, 2);
  115. luaL_check_type(L, 1, LUA_TTABLE);
  116. luaL_arg_check(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil/table expected");
  117. lua_settop(L, 2);
  118. lua_setmetatable(L, 1);
  119. }
  120. return 1;
  121. }
  122. static int luaB_globals (lua_State *L) {
  123. lua_getglobals(L); /* value to be returned */
  124. if (!lua_isnone(L, 1)) {
  125. luaL_check_type(L, 1, LUA_TTABLE);
  126. lua_pushvalue(L, 1); /* new table of globals */
  127. lua_setglobals(L);
  128. }
  129. return 1;
  130. }
  131. static int luaB_rawget (lua_State *L) {
  132. luaL_check_type(L, 1, LUA_TTABLE);
  133. luaL_check_any(L, 2);
  134. lua_rawget(L, 1);
  135. return 1;
  136. }
  137. static int luaB_rawset (lua_State *L) {
  138. luaL_check_type(L, 1, LUA_TTABLE);
  139. luaL_check_any(L, 2);
  140. luaL_check_any(L, 3);
  141. lua_rawset(L, 1);
  142. return 1;
  143. }
  144. static int luaB_gcinfo (lua_State *L) {
  145. lua_pushnumber(L, lua_getgccount(L));
  146. lua_pushnumber(L, lua_getgcthreshold(L));
  147. return 2;
  148. }
  149. static int luaB_collectgarbage (lua_State *L) {
  150. lua_setgcthreshold(L, luaL_opt_int(L, 1, 0));
  151. return 0;
  152. }
  153. static int luaB_type (lua_State *L) {
  154. luaL_check_any(L, 1);
  155. lua_pushstring(L, lua_typename(L, lua_type(L, 1)));
  156. return 1;
  157. }
  158. static int luaB_next (lua_State *L) {
  159. luaL_check_type(L, 1, LUA_TTABLE);
  160. lua_settop(L, 2); /* create a 2nd argument if there isn't one */
  161. if (lua_next(L, 1))
  162. return 2;
  163. else {
  164. lua_pushnil(L);
  165. return 1;
  166. }
  167. }
  168. static int passresults (lua_State *L, int status, int oldtop) {
  169. if (status == 0) {
  170. int nresults = lua_gettop(L) - oldtop;
  171. if (nresults > 0)
  172. return nresults; /* results are already on the stack */
  173. else {
  174. lua_newuserdatabox(L, NULL); /* at least one result to signal no errors */
  175. return 1;
  176. }
  177. }
  178. else { /* error */
  179. lua_pushnil(L);
  180. lua_pushstring(L, luaL_errstr(status)); /* error code */
  181. return 2;
  182. }
  183. }
  184. static int luaB_dostring (lua_State *L) {
  185. int oldtop = lua_gettop(L);
  186. size_t l;
  187. const char *s = luaL_check_lstr(L, 1, &l);
  188. const char *chunkname = luaL_opt_string(L, 2, s);
  189. return passresults(L, lua_dobuffer(L, s, l, chunkname), oldtop);
  190. }
  191. static int luaB_loadstring (lua_State *L) {
  192. int oldtop = lua_gettop(L);
  193. size_t l;
  194. const char *s = luaL_check_lstr(L, 1, &l);
  195. const char *chunkname = luaL_opt_string(L, 2, s);
  196. return passresults(L, lua_loadbuffer(L, s, l, chunkname), oldtop);
  197. }
  198. static int luaB_dofile (lua_State *L) {
  199. int oldtop = lua_gettop(L);
  200. const char *fname = luaL_opt_string(L, 1, NULL);
  201. return passresults(L, lua_dofile(L, fname), oldtop);
  202. }
  203. static int luaB_loadfile (lua_State *L) {
  204. int oldtop = lua_gettop(L);
  205. const char *fname = luaL_opt_string(L, 1, NULL);
  206. return passresults(L, lua_loadfile(L, fname), oldtop);
  207. }
  208. static int luaB_assert (lua_State *L) {
  209. luaL_check_any(L, 1);
  210. if (!lua_toboolean(L, 1))
  211. luaL_verror(L, "assertion failed! %.90s", luaL_opt_string(L, 2, ""));
  212. lua_settop(L, 1);
  213. return 1;
  214. }
  215. #define LUA_PATH "LUA_PATH"
  216. #define LUA_PATH_SEP ";"
  217. #ifndef LUA_PATH_DEFAULT
  218. #define LUA_PATH_DEFAULT "./"
  219. #endif
  220. static int luaB_require (lua_State *L) {
  221. const char *path;
  222. luaL_check_string(L, 1);
  223. lua_settop(L, 1);
  224. lua_getglobal(L, LUA_PATH); /* get path */
  225. if (lua_isstring(L, 2)) /* is LUA_PATH defined? */
  226. path = lua_tostring(L, 2);
  227. else { /* LUA_PATH not defined */
  228. lua_pop(L, 1); /* pop old global value */
  229. path = getenv(LUA_PATH); /* try environment variable */
  230. if (path == NULL) path = LUA_PATH_DEFAULT; /* else use default */
  231. lua_pushstring(L, path);
  232. lua_pushvalue(L, -1); /* duplicate to leave a copy on stack */
  233. lua_setglobal(L, LUA_PATH);
  234. }
  235. lua_pushvalue(L, 1); /* check package's name in book-keeping table */
  236. lua_gettable(L, lua_upvalueindex(1));
  237. if (!lua_isnil(L, -1)) /* is it there? */
  238. return 0; /* package is already loaded */
  239. else { /* must load it */
  240. for (;;) { /* traverse path */
  241. int res;
  242. int l = strcspn(path, LUA_PATH_SEP); /* find separator */
  243. lua_pushlstring(L, path, l); /* directory name */
  244. lua_pushvalue(L, 1); /* package name */
  245. lua_concat(L, 2); /* concat directory with package name */
  246. res = lua_dofile(L, lua_tostring(L, -1)); /* try to load it */
  247. lua_settop(L, 2); /* pop string and eventual results from dofile */
  248. if (res == 0) break; /* ok; file done */
  249. else if (res != LUA_ERRFILE)
  250. lua_error(L, NULL); /* error running package; propagate it */
  251. if (*(path+l) == '\0') /* no more directories? */
  252. luaL_verror(L, "could not load package `%.20s' from path `%.200s'",
  253. lua_tostring(L, 1), lua_tostring(L, 2));
  254. path += l+1; /* try next directory */
  255. }
  256. }
  257. lua_pushvalue(L, 1);
  258. lua_pushnumber(L, 1);
  259. lua_settable(L, lua_upvalueindex(1)); /* mark it as loaded */
  260. return 0;
  261. }
  262. static int aux_unpack (lua_State *L, int arg) {
  263. int n, i;
  264. luaL_check_type(L, arg, LUA_TTABLE);
  265. n = lua_getn(L, arg);
  266. luaL_check_stack(L, n, "table too big to unpack");
  267. for (i=1; i<=n; i++) /* push arg[1...n] */
  268. lua_rawgeti(L, arg, i);
  269. return n;
  270. }
  271. static int luaB_unpack (lua_State *L) {
  272. return aux_unpack(L, 1);
  273. }
  274. static int luaB_call (lua_State *L) {
  275. int oldtop;
  276. const char *options = luaL_opt_string(L, 3, "");
  277. int err = 0; /* index of old error method */
  278. int status;
  279. int n;
  280. if (!lua_isnone(L, 4)) { /* set new error method */
  281. lua_getglobal(L, LUA_ERRORMESSAGE);
  282. err = lua_gettop(L); /* get index */
  283. lua_pushvalue(L, 4);
  284. lua_setglobal(L, LUA_ERRORMESSAGE);
  285. }
  286. oldtop = lua_gettop(L); /* top before function-call preparation */
  287. /* push function */
  288. lua_pushvalue(L, 1);
  289. n = aux_unpack(L, 2); /* push arg[1...n] */
  290. status = lua_call(L, n, LUA_MULTRET);
  291. if (err != 0) { /* restore old error method */
  292. lua_pushvalue(L, err);
  293. lua_setglobal(L, LUA_ERRORMESSAGE);
  294. }
  295. if (status != 0) { /* error in call? */
  296. if (strchr(options, 'x'))
  297. lua_pushnil(L); /* return nil to signal the error */
  298. else
  299. lua_error(L, NULL); /* propagate error without additional messages */
  300. return 1;
  301. }
  302. if (strchr(options, 'p')) /* pack results? */
  303. lua_error(L, "obsolete option `p' in `call'");
  304. return lua_gettop(L) - oldtop; /* results are already on the stack */
  305. }
  306. static int luaB_tostring (lua_State *L) {
  307. char buff[64];
  308. switch (lua_type(L, 1)) {
  309. case LUA_TNUMBER:
  310. lua_pushstring(L, lua_tostring(L, 1));
  311. return 1;
  312. case LUA_TSTRING:
  313. lua_pushvalue(L, 1);
  314. return 1;
  315. case LUA_TBOOLEAN:
  316. lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
  317. return 1;
  318. case LUA_TTABLE:
  319. sprintf(buff, "%.40s: %p", lua_typename(L, lua_type(L, 1)),
  320. lua_topointer(L, 1));
  321. break;
  322. case LUA_TFUNCTION:
  323. sprintf(buff, "function: %p", lua_topointer(L, 1));
  324. break;
  325. case LUA_TUSERDATA: {
  326. const char *t = lua_typename(L, lua_type(L, 1));
  327. if (strcmp(t, "userdata") == 0)
  328. sprintf(buff, "userdata: %p", lua_touserdata(L, 1));
  329. else
  330. sprintf(buff, "%.40s: %p", t, lua_touserdata(L, 1));
  331. break;
  332. }
  333. case LUA_TNIL:
  334. lua_pushliteral(L, "nil");
  335. return 1;
  336. default:
  337. luaL_argerror(L, 1, "value expected");
  338. }
  339. lua_pushstring(L, buff);
  340. return 1;
  341. }
  342. static const luaL_reg base_funcs[] = {
  343. {LUA_ALERT, luaB__ALERT},
  344. {LUA_ERRORMESSAGE, luaB__ERRORMESSAGE},
  345. {"error", luaB_error},
  346. {"metatable", luaB_metatable},
  347. {"globals", luaB_globals},
  348. {"next", luaB_next},
  349. {"print", luaB_print},
  350. {"tonumber", luaB_tonumber},
  351. {"tostring", luaB_tostring},
  352. {"type", luaB_type},
  353. {"assert", luaB_assert},
  354. {"unpack", luaB_unpack},
  355. {"rawget", luaB_rawget},
  356. {"rawset", luaB_rawset},
  357. {"call", luaB_call},
  358. {"collectgarbage", luaB_collectgarbage},
  359. {"gcinfo", luaB_gcinfo},
  360. {"loadfile", luaB_loadfile},
  361. {"loadstring", luaB_loadstring},
  362. {"dofile", luaB_dofile},
  363. {"dostring", luaB_dostring},
  364. {NULL, NULL}
  365. };
  366. static void base_open (lua_State *L) {
  367. lua_pushliteral(L, "_G");
  368. lua_pushvalue(L, LUA_GLOBALSINDEX);
  369. luaL_openlib(L, base_funcs); /* open lib into global table */
  370. lua_pushliteral(L, "_VERSION");
  371. lua_pushliteral(L, LUA_VERSION);
  372. lua_settable(L, -3); /* set global _VERSION */
  373. lua_settable(L, -1); /* set global _G */
  374. }
  375. /*
  376. ** {======================================================
  377. ** Coroutine library
  378. ** =======================================================
  379. */
  380. static int luaB_resume (lua_State *L) {
  381. lua_State *co = (lua_State *)lua_touserdata(L, lua_upvalueindex(1));
  382. if (lua_resume(L, co) != 0)
  383. lua_error(L, "error running co-routine");
  384. return lua_gettop(L);
  385. }
  386. static int gc_coroutine (lua_State *L) {
  387. lua_State *co = (lua_State *)lua_touserdata(L, 1);
  388. lua_closethread(L, co);
  389. return 0;
  390. }
  391. static int luaB_coroutine (lua_State *L) {
  392. lua_State *NL;
  393. int ref;
  394. int i;
  395. int n = lua_gettop(L);
  396. luaL_arg_check(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
  397. "Lua function expected");
  398. NL = lua_newthread(L);
  399. if (NL == NULL) lua_error(L, "unable to create new thread");
  400. /* move function and arguments from L to NL */
  401. for (i=0; i<n; i++) {
  402. ref = lua_ref(L, 1);
  403. lua_getref(NL, ref);
  404. lua_insert(NL, 1);
  405. lua_unref(L, ref);
  406. }
  407. lua_cobegin(NL, n-1);
  408. lua_newuserdatabox(L, NL);
  409. lua_pushliteral(L, "Coroutine");
  410. lua_rawget(L, LUA_REGISTRYINDEX);
  411. lua_setmetatable(L, -2);
  412. lua_pushcclosure(L, luaB_resume, 1);
  413. return 1;
  414. }
  415. static int luaB_yield (lua_State *L) {
  416. return lua_yield(L, lua_gettop(L));
  417. }
  418. static const luaL_reg co_funcs[] = {
  419. {"create", luaB_coroutine},
  420. {"yield", luaB_yield},
  421. {NULL, NULL}
  422. };
  423. static void co_open (lua_State *L) {
  424. luaL_opennamedlib(L, "co", co_funcs);
  425. /* create metatable for coroutines */
  426. lua_pushliteral(L, "Coroutine");
  427. lua_newtable(L);
  428. lua_pushliteral(L, "__gc");
  429. lua_pushcfunction(L, gc_coroutine);
  430. lua_rawset(L, -3);
  431. lua_rawset(L, LUA_REGISTRYINDEX);
  432. }
  433. /* }====================================================== */
  434. /*
  435. ** {======================================================
  436. ** Auxiliar table-related functions
  437. */
  438. static int luaB_foreachi (lua_State *L) {
  439. int n, i;
  440. luaL_check_type(L, 1, LUA_TTABLE);
  441. luaL_check_type(L, 2, LUA_TFUNCTION);
  442. n = lua_getn(L, 1);
  443. for (i=1; i<=n; i++) {
  444. lua_pushvalue(L, 2); /* function */
  445. lua_pushnumber(L, i); /* 1st argument */
  446. lua_rawgeti(L, 1, i); /* 2nd argument */
  447. lua_rawcall(L, 2, 1);
  448. if (!lua_isnil(L, -1))
  449. return 1;
  450. lua_pop(L, 1); /* remove nil result */
  451. }
  452. return 0;
  453. }
  454. static int luaB_foreach (lua_State *L) {
  455. luaL_check_type(L, 1, LUA_TTABLE);
  456. luaL_check_type(L, 2, LUA_TFUNCTION);
  457. lua_pushnil(L); /* first key */
  458. for (;;) {
  459. if (lua_next(L, 1) == 0)
  460. return 0;
  461. lua_pushvalue(L, 2); /* function */
  462. lua_pushvalue(L, -3); /* key */
  463. lua_pushvalue(L, -3); /* value */
  464. lua_rawcall(L, 2, 1);
  465. if (!lua_isnil(L, -1))
  466. return 1;
  467. lua_pop(L, 2); /* remove value and result */
  468. }
  469. }
  470. static void aux_setn (lua_State *L, int t, int n) {
  471. lua_pushliteral(L, "n");
  472. lua_pushnumber(L, n);
  473. lua_rawset(L, t);
  474. }
  475. static int luaB_getn (lua_State *L) {
  476. luaL_check_type(L, 1, LUA_TTABLE);
  477. lua_pushnumber(L, lua_getn(L, 1));
  478. return 1;
  479. }
  480. static int luaB_tinsert (lua_State *L) {
  481. int v = lua_gettop(L); /* number of arguments */
  482. int n, pos;
  483. luaL_check_type(L, 1, LUA_TTABLE);
  484. n = lua_getn(L, 1);
  485. if (v == 2) /* called with only 2 arguments */
  486. pos = n+1;
  487. else {
  488. v = 3; /* function may be called with more than 3 args */
  489. pos = luaL_check_int(L, 2); /* 2nd argument is the position */
  490. }
  491. if (pos > n+1) n = pos-1;
  492. aux_setn(L, 1, n+1); /* t.n = n+1 */
  493. for (; n>=pos; n--) {
  494. lua_rawgeti(L, 1, n);
  495. lua_rawseti(L, 1, n+1); /* t[n+1] = t[n] */
  496. }
  497. lua_pushvalue(L, v);
  498. lua_rawseti(L, 1, pos); /* t[pos] = v */
  499. return 0;
  500. }
  501. static int luaB_tremove (lua_State *L) {
  502. int pos, n;
  503. luaL_check_type(L, 1, LUA_TTABLE);
  504. n = lua_getn(L, 1);
  505. pos = luaL_opt_int(L, 2, n);
  506. if (n <= 0) return 0; /* table is `empty' */
  507. aux_setn(L, 1, n-1); /* t.n = n-1 */
  508. lua_rawgeti(L, 1, pos); /* result = t[pos] */
  509. for ( ;pos<n; pos++) {
  510. lua_rawgeti(L, 1, pos+1);
  511. lua_rawseti(L, 1, pos); /* a[pos] = a[pos+1] */
  512. }
  513. lua_pushnil(L);
  514. lua_rawseti(L, 1, n); /* t[n] = nil */
  515. return 1;
  516. }
  517. /*
  518. ** {======================================================
  519. ** Quicksort
  520. ** (based on `Algorithms in MODULA-3', Robert Sedgewick;
  521. ** Addison-Wesley, 1993.)
  522. */
  523. static void set2 (lua_State *L, int i, int j) {
  524. lua_rawseti(L, 1, i);
  525. lua_rawseti(L, 1, j);
  526. }
  527. static int sort_comp (lua_State *L, int a, int b) {
  528. /* WARNING: the caller (auxsort) must ensure stack space */
  529. if (!lua_isnil(L, 2)) { /* function? */
  530. int res;
  531. lua_pushvalue(L, 2);
  532. lua_pushvalue(L, a-1); /* -1 to compensate function */
  533. lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */
  534. lua_rawcall(L, 2, 1);
  535. res = lua_toboolean(L, -1);
  536. lua_pop(L, 1);
  537. return res;
  538. }
  539. else /* a < b? */
  540. return lua_lessthan(L, a, b);
  541. }
  542. static void auxsort (lua_State *L, int l, int u) {
  543. while (l < u) { /* for tail recursion */
  544. int i, j;
  545. /* sort elements a[l], a[(l+u)/2] and a[u] */
  546. lua_rawgeti(L, 1, l);
  547. lua_rawgeti(L, 1, u);
  548. if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */
  549. set2(L, l, u); /* swap a[l] - a[u] */
  550. else
  551. lua_pop(L, 2);
  552. if (u-l == 1) break; /* only 2 elements */
  553. i = (l+u)/2;
  554. lua_rawgeti(L, 1, i);
  555. lua_rawgeti(L, 1, l);
  556. if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */
  557. set2(L, i, l);
  558. else {
  559. lua_pop(L, 1); /* remove a[l] */
  560. lua_rawgeti(L, 1, u);
  561. if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */
  562. set2(L, i, u);
  563. else
  564. lua_pop(L, 2);
  565. }
  566. if (u-l == 2) break; /* only 3 elements */
  567. lua_rawgeti(L, 1, i); /* Pivot */
  568. lua_pushvalue(L, -1);
  569. lua_rawgeti(L, 1, u-1);
  570. set2(L, i, u-1);
  571. /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
  572. i = l; j = u-1;
  573. for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */
  574. /* repeat ++i until a[i] >= P */
  575. while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
  576. if (i>u) lua_error(L, "invalid order function for sorting");
  577. lua_pop(L, 1); /* remove a[i] */
  578. }
  579. /* repeat --j until a[j] <= P */
  580. while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
  581. if (j<l) lua_error(L, "invalid order function for sorting");
  582. lua_pop(L, 1); /* remove a[j] */
  583. }
  584. if (j<i) {
  585. lua_pop(L, 3); /* pop pivot, a[i], a[j] */
  586. break;
  587. }
  588. set2(L, i, j);
  589. }
  590. lua_rawgeti(L, 1, u-1);
  591. lua_rawgeti(L, 1, i);
  592. set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */
  593. /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
  594. /* adjust so that smaller half is in [j..i] and larger one in [l..u] */
  595. if (i-l < u-i) {
  596. j=l; i=i-1; l=i+2;
  597. }
  598. else {
  599. j=i+1; i=u; u=j-2;
  600. }
  601. auxsort(L, j, i); /* call recursively the smaller one */
  602. } /* repeat the routine for the larger one */
  603. }
  604. static int luaB_sort (lua_State *L) {
  605. int n;
  606. luaL_check_type(L, 1, LUA_TTABLE);
  607. n = lua_getn(L, 1);
  608. if (!lua_isnone(L, 2)) /* is there a 2nd argument? */
  609. luaL_check_type(L, 2, LUA_TFUNCTION);
  610. lua_settop(L, 2); /* make sure there is two arguments */
  611. auxsort(L, 1, n);
  612. return 0;
  613. }
  614. /* }====================================================== */
  615. static const luaL_reg array_funcs[] = {
  616. {"foreach", luaB_foreach},
  617. {"foreachi", luaB_foreachi},
  618. {"getn", luaB_getn},
  619. {"sort", luaB_sort},
  620. {"insert", luaB_tinsert},
  621. {"remove", luaB_tremove},
  622. {NULL, NULL}
  623. };
  624. /* }====================================================== */
  625. LUALIB_API int lua_baselibopen (lua_State *L) {
  626. base_open(L);
  627. co_open(L);
  628. luaL_opennamedlib(L, "A", array_funcs);
  629. /* `require' needs an empty table as upvalue */
  630. lua_newtable(L);
  631. lua_pushcclosure(L, luaB_require, 1);
  632. lua_setglobal(L, "require");
  633. return 0;
  634. }