lbaselib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. /*
  2. ** $Id: lbaselib.c,v 1.162 2004/12/07 18:31:34 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. #define lbaselib_c
  11. #define LUA_LIB
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. /*
  16. ** If your system does not support `stdout', you can just remove this function.
  17. ** If you need, you can define your own `print' function, following this
  18. ** model but changing `fputs' to put the strings at a proper place
  19. ** (a console window or a log file, for instance).
  20. */
  21. static int luaB_print (lua_State *L) {
  22. int n = lua_gettop(L); /* number of arguments */
  23. int i;
  24. lua_getglobal(L, "tostring");
  25. for (i=1; i<=n; i++) {
  26. const char *s;
  27. lua_pushvalue(L, -1); /* function to be called */
  28. lua_pushvalue(L, i); /* value to print */
  29. lua_call(L, 1, 1);
  30. s = lua_tostring(L, -1); /* get result */
  31. if (s == NULL)
  32. return luaL_error(L, "`tostring' must return a string to `print'");
  33. if (i>1) fputs("\t", stdout);
  34. fputs(s, stdout);
  35. lua_pop(L, 1); /* pop result */
  36. }
  37. fputs("\n", stdout);
  38. return 0;
  39. }
  40. static int luaB_tonumber (lua_State *L) {
  41. int base = luaL_optint(L, 2, 10);
  42. if (base == 10) { /* standard conversion */
  43. luaL_checkany(L, 1);
  44. if (lua_isnumber(L, 1)) {
  45. lua_pushnumber(L, lua_tonumber(L, 1));
  46. return 1;
  47. }
  48. }
  49. else {
  50. const char *s1 = luaL_checkstring(L, 1);
  51. char *s2;
  52. unsigned long n;
  53. luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
  54. n = strtoul(s1, &s2, base);
  55. if (s1 != s2) { /* at least one valid digit? */
  56. while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */
  57. if (*s2 == '\0') { /* no invalid trailing characters? */
  58. lua_pushnumber(L, (lua_Number)n);
  59. return 1;
  60. }
  61. }
  62. }
  63. lua_pushnil(L); /* else not a number */
  64. return 1;
  65. }
  66. static int luaB_error (lua_State *L) {
  67. int level = luaL_optint(L, 2, 1);
  68. lua_settop(L, 1);
  69. if (lua_isstring(L, 1) && level > 0) { /* add extra information? */
  70. luaL_where(L, level);
  71. lua_pushvalue(L, 1);
  72. lua_concat(L, 2);
  73. }
  74. return lua_error(L);
  75. }
  76. static int luaB_getmetatable (lua_State *L) {
  77. luaL_checkany(L, 1);
  78. if (!lua_getmetatable(L, 1)) {
  79. lua_pushnil(L);
  80. return 1; /* no metatable */
  81. }
  82. luaL_getmetafield(L, 1, "__metatable");
  83. return 1; /* returns either __metatable field (if present) or metatable */
  84. }
  85. static int luaB_setmetatable (lua_State *L) {
  86. int t = lua_type(L, 2);
  87. luaL_checktype(L, 1, LUA_TTABLE);
  88. luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
  89. "nil or table expected");
  90. if (luaL_getmetafield(L, 1, "__metatable"))
  91. luaL_error(L, "cannot change a protected metatable");
  92. lua_settop(L, 2);
  93. lua_setmetatable(L, 1);
  94. return 1;
  95. }
  96. static void getfunc (lua_State *L) {
  97. if (lua_isfunction(L, 1)) lua_pushvalue(L, 1);
  98. else {
  99. lua_Debug ar;
  100. int level = luaL_optint(L, 1, 1);
  101. luaL_argcheck(L, level >= 0, 1, "level must be non-negative");
  102. if (lua_getstack(L, level, &ar) == 0)
  103. luaL_argerror(L, 1, "invalid level");
  104. lua_getinfo(L, "f", &ar);
  105. if (lua_isnil(L, -1))
  106. luaL_error(L, "no function environment for tail call at level %d",
  107. level);
  108. }
  109. }
  110. static int luaB_getfenv (lua_State *L) {
  111. getfunc(L);
  112. lua_getfenv(L, -1);
  113. return 1;
  114. }
  115. static int luaB_setfenv (lua_State *L) {
  116. luaL_checktype(L, 2, LUA_TTABLE);
  117. getfunc(L);
  118. lua_pushvalue(L, 2);
  119. if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0) {
  120. lua_replace(L, LUA_GLOBALSINDEX);
  121. return 0;
  122. }
  123. else if (lua_setfenv(L, -2) == 0)
  124. luaL_error(L, "`setfenv' cannot change environment of given function");
  125. return 1;
  126. }
  127. static int luaB_rawequal (lua_State *L) {
  128. luaL_checkany(L, 1);
  129. luaL_checkany(L, 2);
  130. lua_pushboolean(L, lua_rawequal(L, 1, 2));
  131. return 1;
  132. }
  133. static int luaB_rawget (lua_State *L) {
  134. luaL_checktype(L, 1, LUA_TTABLE);
  135. luaL_checkany(L, 2);
  136. lua_rawget(L, 1);
  137. return 1;
  138. }
  139. static int luaB_rawset (lua_State *L) {
  140. luaL_checktype(L, 1, LUA_TTABLE);
  141. luaL_checkany(L, 2);
  142. luaL_checkany(L, 3);
  143. lua_rawset(L, 1);
  144. return 1;
  145. }
  146. static int luaB_gcinfo (lua_State *L) {
  147. lua_pushinteger(L, lua_getgccount(L));
  148. return 1;
  149. }
  150. static int luaB_collectgarbage (lua_State *L) {
  151. static const char *const opts[] = {"stop", "restart", "collect",
  152. "count", "step", "setpace", "setincmode", NULL};
  153. static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
  154. LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPACE, LUA_GCSETINCMODE};
  155. int o = luaL_findstring(luaL_optstring(L, 1, "collect"), opts);
  156. int ex = luaL_optint(L, 2, 0);
  157. luaL_argcheck(L, o >= 0, 1, "invalid option");
  158. lua_pushinteger(L, lua_gc(L, optsnum[o], ex));
  159. return 1;
  160. }
  161. static int luaB_type (lua_State *L) {
  162. luaL_checkany(L, 1);
  163. lua_pushstring(L, luaL_typename(L, 1));
  164. return 1;
  165. }
  166. static int luaB_next (lua_State *L) {
  167. luaL_checktype(L, 1, LUA_TTABLE);
  168. lua_settop(L, 2); /* create a 2nd argument if there isn't one */
  169. if (lua_next(L, 1))
  170. return 2;
  171. else {
  172. lua_pushnil(L);
  173. return 1;
  174. }
  175. }
  176. static int luaB_pairs (lua_State *L) {
  177. luaL_checktype(L, 1, LUA_TTABLE);
  178. lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
  179. lua_pushvalue(L, 1); /* state, */
  180. lua_pushnil(L); /* and initial value */
  181. return 3;
  182. }
  183. static int ipairsaux (lua_State *L) {
  184. int i = luaL_checkint(L, 2);
  185. luaL_checktype(L, 1, LUA_TTABLE);
  186. i++; /* next value */
  187. lua_pushinteger(L, i);
  188. lua_rawgeti(L, 1, i);
  189. return (lua_isnil(L, -1)) ? 0 : 2;
  190. }
  191. static int luaB_ipairs (lua_State *L) {
  192. luaL_checktype(L, 1, LUA_TTABLE);
  193. lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
  194. lua_pushvalue(L, 1); /* state, */
  195. lua_pushinteger(L, LUA_FIRSTINDEX - 1); /* and initial value */
  196. return 3;
  197. }
  198. static int load_aux (lua_State *L, int status) {
  199. if (status == 0) /* OK? */
  200. return 1;
  201. else {
  202. lua_pushnil(L);
  203. lua_insert(L, -2); /* put before error message */
  204. return 2; /* return nil plus error message */
  205. }
  206. }
  207. static int luaB_loadstring (lua_State *L) {
  208. size_t l;
  209. const char *s = luaL_checklstring(L, 1, &l);
  210. const char *chunkname = luaL_optstring(L, 2, s);
  211. return load_aux(L, luaL_loadbuffer(L, s, l, chunkname));
  212. }
  213. static int luaB_loadfile (lua_State *L) {
  214. const char *fname = luaL_optstring(L, 1, NULL);
  215. const char *path = luaL_optstring(L, 2, NULL);
  216. int status;
  217. if (path == NULL)
  218. status = luaL_loadfile(L, fname);
  219. else {
  220. fname = luaL_searchpath(L, fname, path);
  221. status = (fname) ? luaL_loadfile(L, fname) : 1;
  222. }
  223. return load_aux(L, status);
  224. }
  225. /*
  226. ** Reader for generic `load' function: `lua_load' uses the
  227. ** stack for internal stuff, so the reader cannot change the
  228. ** stack top. Instead, it keeps its resulting string in a
  229. ** reserved slot inside the stack.
  230. */
  231. static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
  232. luaL_checkstack(L, 2, "too many nested functions");
  233. lua_pushvalue(L, 1); /* get function */
  234. lua_call(L, 0, 1); /* call it */
  235. if (lua_isnil(L, -1)) {
  236. *size = 0;
  237. return NULL;
  238. }
  239. else if (lua_isstring(L, -1)) {
  240. const char *res;
  241. lua_replace(L, 3); /* save string in a reserved stack slot */
  242. res = lua_tostring(L, 3);
  243. *size = lua_strlen(L, 3);
  244. return res;
  245. }
  246. else luaL_error(L, "reader function must return a string");
  247. return NULL; /* to avoid warnings */
  248. }
  249. static int luaB_load (lua_State *L) {
  250. int status;
  251. const char *cname = luaL_optstring(L, 2, "=(load)");
  252. luaL_checktype(L, 1, LUA_TFUNCTION);
  253. lua_settop(L, 3); /* function, eventual name, plus one reserved slot */
  254. status = lua_load(L, generic_reader, NULL, cname);
  255. return load_aux(L, status);
  256. }
  257. static int luaB_dofile (lua_State *L) {
  258. const char *fname = luaL_optstring(L, 1, NULL);
  259. int n = lua_gettop(L);
  260. if (luaL_loadfile(L, fname) != 0) lua_error(L);
  261. lua_call(L, 0, LUA_MULTRET);
  262. return lua_gettop(L) - n;
  263. }
  264. static int luaB_assert (lua_State *L) {
  265. luaL_checkany(L, 1);
  266. if (!lua_toboolean(L, 1))
  267. return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
  268. return lua_gettop(L);
  269. }
  270. static int luaB_unpack (lua_State *L) {
  271. int i = luaL_optint(L, 2, LUA_FIRSTINDEX);
  272. int e = luaL_optint(L, 3, -1);
  273. int n;
  274. luaL_checktype(L, 1, LUA_TTABLE);
  275. if (e == -1)
  276. e = luaL_getn(L, 1) + LUA_FIRSTINDEX - 1;
  277. n = e - i + 1; /* number of elements */
  278. if (n <= 0) return 0; /* empty range */
  279. luaL_checkstack(L, n, "table too big to unpack");
  280. for (; i<=e; i++) /* push arg[i...e] */
  281. lua_rawgeti(L, 1, i);
  282. return n;
  283. }
  284. static int luaB_select (lua_State *L) {
  285. int n = lua_gettop(L);
  286. if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
  287. lua_pushinteger(L, n-1);
  288. return 1;
  289. }
  290. else {
  291. int i = luaL_checkint(L, 1);
  292. if (i <= 0) i = 1;
  293. else if (i >= n) i = n;
  294. return n - i;
  295. }
  296. }
  297. static int luaB_pcall (lua_State *L) {
  298. int status;
  299. luaL_checkany(L, 1);
  300. status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
  301. lua_pushboolean(L, (status == 0));
  302. lua_insert(L, 1);
  303. return lua_gettop(L); /* return status + all results */
  304. }
  305. static int luaB_xpcall (lua_State *L) {
  306. int status;
  307. luaL_checkany(L, 2);
  308. lua_settop(L, 2);
  309. lua_insert(L, 1); /* put error function under function to be called */
  310. status = lua_pcall(L, 0, LUA_MULTRET, 1);
  311. lua_pushboolean(L, (status == 0));
  312. lua_replace(L, 1);
  313. return lua_gettop(L); /* return status + all results */
  314. }
  315. static int luaB_tostring (lua_State *L) {
  316. luaL_checkany(L, 1);
  317. if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */
  318. return 1; /* use its value */
  319. switch (lua_type(L, 1)) {
  320. case LUA_TNUMBER:
  321. lua_pushstring(L, lua_tostring(L, 1));
  322. break;
  323. case LUA_TSTRING:
  324. lua_pushvalue(L, 1);
  325. break;
  326. case LUA_TBOOLEAN:
  327. lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
  328. break;
  329. case LUA_TNIL:
  330. lua_pushliteral(L, "nil");
  331. break;
  332. default:
  333. lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1));
  334. break;
  335. }
  336. return 1;
  337. }
  338. static int luaB_newproxy (lua_State *L) {
  339. lua_settop(L, 1);
  340. lua_newuserdata(L, 0); /* create proxy */
  341. if (lua_toboolean(L, 1) == 0)
  342. return 1; /* no metatable */
  343. else if (lua_isboolean(L, 1)) {
  344. lua_newtable(L); /* create a new metatable `m' ... */
  345. lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
  346. lua_pushboolean(L, 1);
  347. lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
  348. }
  349. else {
  350. int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
  351. if (lua_getmetatable(L, 1)) {
  352. lua_rawget(L, lua_upvalueindex(1));
  353. validproxy = lua_toboolean(L, -1);
  354. lua_pop(L, 1); /* remove value */
  355. }
  356. luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
  357. lua_getmetatable(L, 1); /* metatable is valid; get it */
  358. }
  359. lua_setmetatable(L, 2);
  360. return 1;
  361. }
  362. static const luaL_reg base_funcs[] = {
  363. {"error", luaB_error},
  364. {"getmetatable", luaB_getmetatable},
  365. {"setmetatable", luaB_setmetatable},
  366. {"getfenv", luaB_getfenv},
  367. {"setfenv", luaB_setfenv},
  368. {"next", luaB_next},
  369. {"print", luaB_print},
  370. {"tonumber", luaB_tonumber},
  371. {"tostring", luaB_tostring},
  372. {"type", luaB_type},
  373. {"assert", luaB_assert},
  374. {"unpack", luaB_unpack},
  375. {"select", luaB_select},
  376. {"rawequal", luaB_rawequal},
  377. {"rawget", luaB_rawget},
  378. {"rawset", luaB_rawset},
  379. {"pcall", luaB_pcall},
  380. {"xpcall", luaB_xpcall},
  381. {"collectgarbage", luaB_collectgarbage},
  382. {"gcinfo", luaB_gcinfo},
  383. {"loadfile", luaB_loadfile},
  384. {"dofile", luaB_dofile},
  385. {"loadstring", luaB_loadstring},
  386. {"load", luaB_load},
  387. {NULL, NULL}
  388. };
  389. /*
  390. ** {======================================================
  391. ** Coroutine library
  392. ** =======================================================
  393. */
  394. static int auxresume (lua_State *L, lua_State *co, int narg) {
  395. int status;
  396. if (!lua_checkstack(co, narg))
  397. luaL_error(L, "too many arguments to resume");
  398. if (lua_threadstatus(co) == 0 && lua_gettop(co) == 0) {
  399. lua_pushliteral(L, "cannot resume dead coroutine");
  400. return -1; /* error flag */
  401. }
  402. lua_xmove(L, co, narg);
  403. status = lua_resume(co, narg);
  404. if (status == 0 || status == LUA_YIELD) {
  405. int nres = lua_gettop(co);
  406. if (!lua_checkstack(L, nres))
  407. luaL_error(L, "too many results to resume");
  408. lua_xmove(co, L, nres); /* move yielded values */
  409. return nres;
  410. }
  411. else {
  412. lua_xmove(co, L, 1); /* move error message */
  413. return -1; /* error flag */
  414. }
  415. }
  416. static int luaB_coresume (lua_State *L) {
  417. lua_State *co = lua_tothread(L, 1);
  418. int r;
  419. luaL_argcheck(L, co, 1, "coroutine expected");
  420. r = auxresume(L, co, lua_gettop(L) - 1);
  421. if (r < 0) {
  422. lua_pushboolean(L, 0);
  423. lua_insert(L, -2);
  424. return 2; /* return false + error message */
  425. }
  426. else {
  427. lua_pushboolean(L, 1);
  428. lua_insert(L, -(r + 1));
  429. return r + 1; /* return true + `resume' returns */
  430. }
  431. }
  432. static int luaB_auxwrap (lua_State *L) {
  433. lua_State *co = lua_tothread(L, lua_upvalueindex(1));
  434. int r = auxresume(L, co, lua_gettop(L));
  435. if (r < 0) {
  436. if (lua_isstring(L, -1)) { /* error object is a string? */
  437. luaL_where(L, 1); /* add extra info */
  438. lua_insert(L, -2);
  439. lua_concat(L, 2);
  440. }
  441. lua_error(L); /* propagate error */
  442. }
  443. return r;
  444. }
  445. static int luaB_cocreate (lua_State *L) {
  446. lua_State *NL = lua_newthread(L);
  447. luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
  448. "Lua function expected");
  449. lua_pushvalue(L, 1); /* move function to top */
  450. lua_xmove(L, NL, 1); /* move function from L to NL */
  451. return 1;
  452. }
  453. static int luaB_cowrap (lua_State *L) {
  454. luaB_cocreate(L);
  455. lua_pushcclosure(L, luaB_auxwrap, 1);
  456. return 1;
  457. }
  458. static int luaB_yield (lua_State *L) {
  459. return lua_yield(L, lua_gettop(L));
  460. }
  461. static int luaB_costatus (lua_State *L) {
  462. lua_State *co = lua_tothread(L, 1);
  463. luaL_argcheck(L, co, 1, "coroutine expected");
  464. if (L == co) lua_pushliteral(L, "running");
  465. else {
  466. switch (lua_threadstatus(co)) {
  467. case LUA_YIELD:
  468. lua_pushliteral(L, "suspended");
  469. break;
  470. case 0: {
  471. lua_Debug ar;
  472. if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */
  473. lua_pushliteral(L, "normal"); /* it is running */
  474. else if (lua_gettop(co) == 0)
  475. lua_pushliteral(L, "dead");
  476. else
  477. lua_pushliteral(L, "suspended"); /* initial state */
  478. break;
  479. }
  480. default: /* some error occured */
  481. lua_pushliteral(L, "dead");
  482. break;
  483. }
  484. }
  485. return 1;
  486. }
  487. static int luaB_cocurrent (lua_State *L) {
  488. if (lua_pushthread(L))
  489. return 0; /* main thread is not a coroutine */
  490. else
  491. return 1;
  492. }
  493. static const luaL_reg co_funcs[] = {
  494. {"create", luaB_cocreate},
  495. {"wrap", luaB_cowrap},
  496. {"resume", luaB_coresume},
  497. {"yield", luaB_yield},
  498. {"status", luaB_costatus},
  499. {"current", luaB_cocurrent},
  500. {NULL, NULL}
  501. };
  502. /* }====================================================== */
  503. static void auxopen (lua_State *L, const char *name,
  504. lua_CFunction f, lua_CFunction u) {
  505. lua_pushcfunction(L, u);
  506. lua_pushcclosure(L, f, 1);
  507. lua_setfield(L, -2, name);
  508. }
  509. static void base_open (lua_State *L) {
  510. lua_pushvalue(L, LUA_GLOBALSINDEX);
  511. luaL_openlib(L, NULL, base_funcs, 0); /* open lib into global table */
  512. lua_pushliteral(L, LUA_VERSION);
  513. lua_setglobal(L, "_VERSION"); /* set global _VERSION */
  514. /* `ipairs' and `pairs' need auxiliary functions as upvalues */
  515. auxopen(L, "ipairs", luaB_ipairs, ipairsaux);
  516. auxopen(L, "pairs", luaB_pairs, luaB_next);
  517. /* `newproxy' needs a weaktable as upvalue */
  518. lua_newtable(L); /* new table `w' */
  519. lua_pushvalue(L, -1); /* `w' will be its own metatable */
  520. lua_setmetatable(L, -2);
  521. lua_pushliteral(L, "kv");
  522. lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
  523. lua_pushcclosure(L, luaB_newproxy, 1);
  524. lua_setglobal(L, "newproxy"); /* set global `newproxy' */
  525. /* create register._LOADED to track loaded modules */
  526. lua_newtable(L);
  527. lua_setfield(L, LUA_REGISTRYINDEX, "_LOADED");
  528. /* create register._PRELOAD to allow pre-loaded modules */
  529. lua_newtable(L);
  530. lua_setfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
  531. /* set global _G */
  532. lua_pushvalue(L, LUA_GLOBALSINDEX);
  533. lua_setglobal(L, "_G");
  534. }
  535. LUALIB_API int luaopen_base (lua_State *L) {
  536. base_open(L);
  537. luaL_openlib(L, LUA_COLIBNAME, co_funcs, 0);
  538. return 2;
  539. }