lbaselib.c 16 KB

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