lbaselib.c 16 KB

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