lbaselib.c 19 KB

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