lbaselib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. /*
  2. ** $Id: lbaselib.c,v 1.209 2009/02/06 18:38:47 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 luaB_dofile (lua_State *L) {
  272. const char *fname = luaL_optstring(L, 1, NULL);
  273. lua_settop(L, 1);
  274. if (luaL_loadfile(L, fname) != LUA_OK) lua_error(L);
  275. lua_call(L, 0, LUA_MULTRET);
  276. return lua_gettop(L) - 1;
  277. }
  278. static int luaB_assert (lua_State *L) {
  279. luaL_checkany(L, 1);
  280. if (!lua_toboolean(L, 1))
  281. return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
  282. return lua_gettop(L);
  283. }
  284. static int luaB_unpack (lua_State *L) {
  285. int i, e, n;
  286. luaL_checktype(L, 1, LUA_TTABLE);
  287. i = luaL_optint(L, 2, 1);
  288. e = luaL_opt(L, luaL_checkint, 3, (int)lua_objlen(L, 1));
  289. if (i > e) return 0; /* empty range */
  290. n = e - i + 1; /* number of elements */
  291. if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */
  292. return luaL_error(L, "too many results to unpack");
  293. lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */
  294. while (i++ < e) /* push arg[i + 1...e] */
  295. lua_rawgeti(L, 1, i);
  296. return n;
  297. }
  298. static int luaB_select (lua_State *L) {
  299. int n = lua_gettop(L);
  300. if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
  301. lua_pushinteger(L, n-1);
  302. return 1;
  303. }
  304. else {
  305. int i = luaL_checkint(L, 1);
  306. if (i < 0) i = n + i;
  307. else if (i > n) i = n;
  308. luaL_argcheck(L, 1 <= i, 1, "index out of range");
  309. return n - i;
  310. }
  311. }
  312. static int luaB_pcall (lua_State *L) {
  313. int status;
  314. luaL_checkany(L, 1);
  315. status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
  316. lua_pushboolean(L, (status == LUA_OK));
  317. lua_insert(L, 1);
  318. return lua_gettop(L); /* return status + all results */
  319. }
  320. static int luaB_xpcall (lua_State *L) {
  321. int status;
  322. int n = lua_gettop(L);
  323. luaL_argcheck(L, n >= 2, 2, "value expected");
  324. lua_pushvalue(L, 1); /* exchange function... */
  325. lua_pushvalue(L, 2); /* ...and error handler */
  326. lua_replace(L, 1);
  327. lua_replace(L, 2);
  328. status = lua_pcall(L, n - 2, LUA_MULTRET, 1);
  329. lua_pushboolean(L, (status == LUA_OK));
  330. lua_replace(L, 1);
  331. return lua_gettop(L); /* return status + all results */
  332. }
  333. static int luaB_tostring (lua_State *L) {
  334. luaL_checkany(L, 1);
  335. luaL_tolstring(L, 1, NULL);
  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_createtable(L, 0, 1); /* create a new metatable `m' ... */
  345. lua_pushboolean(L, 1);
  346. lua_setfield(L, -2, "__gc"); /* ... m.__gc = false (HACK!!)... */
  347. lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
  348. lua_pushboolean(L, 1);
  349. lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
  350. }
  351. else {
  352. int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
  353. if (lua_getmetatable(L, 1)) {
  354. lua_rawget(L, lua_upvalueindex(1));
  355. validproxy = lua_toboolean(L, -1);
  356. lua_pop(L, 1); /* remove value */
  357. }
  358. luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
  359. lua_getmetatable(L, 1); /* metatable is valid; get it */
  360. }
  361. lua_setmetatable(L, 2);
  362. return 1;
  363. }
  364. static const luaL_Reg base_funcs[] = {
  365. {"assert", luaB_assert},
  366. {"collectgarbage", luaB_collectgarbage},
  367. {"dofile", luaB_dofile},
  368. {"error", luaB_error},
  369. {"gcinfo", luaB_gcinfo},
  370. {"getfenv", luaB_getfenv},
  371. {"getmetatable", luaB_getmetatable},
  372. {"loadfile", luaB_loadfile},
  373. {"load", luaB_load},
  374. {"loadstring", luaB_loadstring},
  375. {"next", luaB_next},
  376. {"pcall", luaB_pcall},
  377. {"print", luaB_print},
  378. {"rawequal", luaB_rawequal},
  379. {"rawget", luaB_rawget},
  380. {"rawset", luaB_rawset},
  381. {"select", luaB_select},
  382. {"setfenv", luaB_setfenv},
  383. {"setmetatable", luaB_setmetatable},
  384. {"tonumber", luaB_tonumber},
  385. {"tostring", luaB_tostring},
  386. {"type", luaB_type},
  387. {"unpack", luaB_unpack},
  388. {"xpcall", luaB_xpcall},
  389. {NULL, NULL}
  390. };
  391. /*
  392. ** {======================================================
  393. ** Coroutine library
  394. ** =======================================================
  395. */
  396. static int auxresume (lua_State *L, lua_State *co, int narg) {
  397. int status;
  398. if (!lua_checkstack(co, narg))
  399. return luaL_error(L, "too many arguments to resume");
  400. if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) {
  401. lua_pushliteral(L, "cannot resume dead coroutine");
  402. return -1; /* error flag */
  403. }
  404. lua_xmove(L, co, narg);
  405. status = lua_resume(co, narg);
  406. if (status == LUA_OK || status == LUA_YIELD) {
  407. int nres = lua_gettop(co);
  408. if (!lua_checkstack(L, nres + 1))
  409. return luaL_error(L, "too many results to resume");
  410. lua_xmove(co, L, nres); /* move yielded values */
  411. return nres;
  412. }
  413. else {
  414. lua_xmove(co, L, 1); /* move error message */
  415. return -1; /* error flag */
  416. }
  417. }
  418. static int luaB_coresume (lua_State *L) {
  419. lua_State *co = lua_tothread(L, 1);
  420. int r;
  421. luaL_argcheck(L, co, 1, "coroutine expected");
  422. r = auxresume(L, co, lua_gettop(L) - 1);
  423. if (r < 0) {
  424. lua_pushboolean(L, 0);
  425. lua_insert(L, -2);
  426. return 2; /* return false + error message */
  427. }
  428. else {
  429. lua_pushboolean(L, 1);
  430. lua_insert(L, -(r + 1));
  431. return r + 1; /* return true + `resume' returns */
  432. }
  433. }
  434. static int luaB_auxwrap (lua_State *L) {
  435. lua_State *co = lua_tothread(L, lua_upvalueindex(1));
  436. int r = auxresume(L, co, lua_gettop(L));
  437. if (r < 0) {
  438. if (lua_isstring(L, -1)) { /* error object is a string? */
  439. luaL_where(L, 1); /* add extra info */
  440. lua_insert(L, -2);
  441. lua_concat(L, 2);
  442. }
  443. lua_error(L); /* propagate error */
  444. }
  445. return r;
  446. }
  447. static int luaB_cocreate (lua_State *L) {
  448. lua_State *NL = lua_newthread(L);
  449. luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
  450. "Lua function expected");
  451. lua_pushvalue(L, 1); /* move function to top */
  452. lua_xmove(L, NL, 1); /* move function from L to NL */
  453. return 1;
  454. }
  455. static int luaB_cowrap (lua_State *L) {
  456. luaB_cocreate(L);
  457. lua_pushcclosure(L, luaB_auxwrap, 1);
  458. return 1;
  459. }
  460. static int luaB_yield (lua_State *L) {
  461. return lua_yield(L, lua_gettop(L));
  462. }
  463. static int luaB_costatus (lua_State *L) {
  464. lua_State *co = lua_tothread(L, 1);
  465. luaL_argcheck(L, co, 1, "coroutine expected");
  466. if (L == co) lua_pushliteral(L, "running");
  467. else {
  468. switch (lua_status(co)) {
  469. case LUA_YIELD:
  470. lua_pushliteral(L, "suspended");
  471. break;
  472. case LUA_OK: {
  473. lua_Debug ar;
  474. if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */
  475. lua_pushliteral(L, "normal"); /* it is running */
  476. else if (lua_gettop(co) == 0)
  477. lua_pushliteral(L, "dead");
  478. else
  479. lua_pushliteral(L, "suspended"); /* initial state */
  480. break;
  481. }
  482. default: /* some error occured */
  483. lua_pushliteral(L, "dead");
  484. break;
  485. }
  486. }
  487. return 1;
  488. }
  489. static int luaB_corunning (lua_State *L) {
  490. int ismain = lua_pushthread(L);
  491. lua_pushboolean(L, ismain);
  492. return 2;
  493. }
  494. static const luaL_Reg co_funcs[] = {
  495. {"create", luaB_cocreate},
  496. {"resume", luaB_coresume},
  497. {"running", luaB_corunning},
  498. {"status", luaB_costatus},
  499. {"wrap", luaB_cowrap},
  500. {"yield", luaB_yield},
  501. {NULL, NULL}
  502. };
  503. /* }====================================================== */
  504. static void auxopen (lua_State *L, const char *name,
  505. lua_CFunction f, lua_CFunction u) {
  506. lua_pushcfunction(L, u);
  507. lua_pushcclosure(L, f, 1);
  508. lua_setfield(L, -2, name);
  509. }
  510. static void base_open (lua_State *L) {
  511. /* set global _G */
  512. lua_pushvalue(L, LUA_GLOBALSINDEX);
  513. lua_setglobal(L, "_G");
  514. /* open lib into global table */
  515. luaL_register(L, "_G", base_funcs);
  516. lua_pushliteral(L, LUA_VERSION);
  517. lua_setglobal(L, "_VERSION"); /* set global _VERSION */
  518. /* `ipairs' and `pairs' need auxiliary functions as upvalues */
  519. auxopen(L, "ipairs", luaB_ipairs, ipairsaux);
  520. auxopen(L, "pairs", luaB_pairs, luaB_next);
  521. /* `newproxy' needs a weaktable as upvalue */
  522. lua_createtable(L, 0, 1); /* new table `w' */
  523. lua_pushvalue(L, -1); /* `w' will be its own metatable */
  524. lua_setmetatable(L, -2);
  525. lua_pushliteral(L, "kv");
  526. lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
  527. lua_pushcclosure(L, luaB_newproxy, 1);
  528. lua_setglobal(L, "newproxy"); /* set global `newproxy' */
  529. }
  530. LUALIB_API int luaopen_base (lua_State *L) {
  531. base_open(L);
  532. luaL_register(L, LUA_COLIBNAME, co_funcs);
  533. return 2;
  534. }