lbaselib.c 16 KB

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