lbaselib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. /*
  2. ** $Id: lbaselib.c,v 1.112 2002/11/26 12:53:29 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. #include "lua.h"
  11. #include "lauxlib.h"
  12. #include "lualib.h"
  13. /*
  14. ** If your system does not support `stdout', you can just remove this function.
  15. ** If you need, you can define your own `print' function, following this
  16. ** model but changing `fputs' to put the strings at a proper place
  17. ** (a console window or a log file, for instance).
  18. */
  19. static int luaB_print (lua_State *L) {
  20. int n = lua_gettop(L); /* number of arguments */
  21. int i;
  22. lua_getglobal(L, "tostring");
  23. for (i=1; i<=n; i++) {
  24. const char *s;
  25. lua_pushvalue(L, -1); /* function to be called */
  26. lua_pushvalue(L, i); /* value to print */
  27. lua_call(L, 1, 1);
  28. s = lua_tostring(L, -1); /* get result */
  29. if (s == NULL)
  30. return luaL_error(L, "`tostring' must return a string to `print'");
  31. if (i>1) fputs("\t", stdout);
  32. fputs(s, stdout);
  33. lua_pop(L, 1); /* pop result */
  34. }
  35. fputs("\n", stdout);
  36. return 0;
  37. }
  38. static int luaB_tonumber (lua_State *L) {
  39. int base = luaL_optint(L, 2, 10);
  40. if (base == 10) { /* standard conversion */
  41. luaL_checkany(L, 1);
  42. if (lua_isnumber(L, 1)) {
  43. lua_pushnumber(L, lua_tonumber(L, 1));
  44. return 1;
  45. }
  46. }
  47. else {
  48. const char *s1 = luaL_checkstring(L, 1);
  49. char *s2;
  50. unsigned long n;
  51. luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
  52. n = strtoul(s1, &s2, base);
  53. if (s1 != s2) { /* at least one valid digit? */
  54. while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */
  55. if (*s2 == '\0') { /* no invalid trailing characters? */
  56. lua_pushnumber(L, n);
  57. return 1;
  58. }
  59. }
  60. }
  61. lua_pushnil(L); /* else not a number */
  62. return 1;
  63. }
  64. static int luaB_error (lua_State *L) {
  65. int level = luaL_optint(L, 2, 1);
  66. luaL_checkany(L, 1);
  67. if (!lua_isstring(L, 1) || level == 0)
  68. lua_pushvalue(L, 1); /* propagate error message without changes */
  69. else { /* 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. }
  106. }
  107. static int aux_getglobals (lua_State *L) {
  108. lua_getglobals(L, -1);
  109. lua_pushliteral(L, "__globals");
  110. lua_rawget(L, -2);
  111. return !lua_isnil(L, -1);
  112. }
  113. static int luaB_getglobals (lua_State *L) {
  114. getfunc(L);
  115. if (!aux_getglobals(L)) /* __globals not defined? */
  116. lua_pop(L, 1); /* remove it, to return real globals */
  117. return 1;
  118. }
  119. static int luaB_setglobals (lua_State *L) {
  120. luaL_checktype(L, 2, LUA_TTABLE);
  121. getfunc(L);
  122. if (aux_getglobals(L)) /* __globals defined? */
  123. luaL_error(L, "cannot change a protected global table");
  124. else
  125. lua_pop(L, 2); /* remove __globals and real global table */
  126. lua_pushvalue(L, 2);
  127. if (lua_setglobals(L, -2) == 0)
  128. luaL_error(L, "cannot change global table of given function");
  129. return 0;
  130. }
  131. static int luaB_rawequal (lua_State *L) {
  132. luaL_checkany(L, 1);
  133. luaL_checkany(L, 2);
  134. lua_pushboolean(L, lua_rawequal(L, 1, 2));
  135. return 1;
  136. }
  137. static int luaB_rawget (lua_State *L) {
  138. luaL_checktype(L, 1, LUA_TTABLE);
  139. luaL_checkany(L, 2);
  140. lua_rawget(L, 1);
  141. return 1;
  142. }
  143. static int luaB_rawset (lua_State *L) {
  144. luaL_checktype(L, 1, LUA_TTABLE);
  145. luaL_checkany(L, 2);
  146. luaL_checkany(L, 3);
  147. lua_rawset(L, 1);
  148. return 1;
  149. }
  150. static int luaB_gcinfo (lua_State *L) {
  151. lua_pushnumber(L, lua_getgccount(L));
  152. lua_pushnumber(L, lua_getgcthreshold(L));
  153. return 2;
  154. }
  155. static int luaB_collectgarbage (lua_State *L) {
  156. lua_setgcthreshold(L, luaL_optint(L, 1, 0));
  157. return 0;
  158. }
  159. static int luaB_type (lua_State *L) {
  160. luaL_checkany(L, 1);
  161. lua_pushstring(L, lua_typename(L, lua_type(L, 1)));
  162. return 1;
  163. }
  164. static int luaB_next (lua_State *L) {
  165. luaL_checktype(L, 1, LUA_TTABLE);
  166. lua_settop(L, 2); /* create a 2nd argument if there isn't one */
  167. if (lua_next(L, 1))
  168. return 2;
  169. else {
  170. lua_pushnil(L);
  171. return 1;
  172. }
  173. }
  174. static int luaB_pairs (lua_State *L) {
  175. luaL_checktype(L, 1, LUA_TTABLE);
  176. lua_pushliteral(L, "next");
  177. lua_rawget(L, LUA_GLOBALSINDEX); /* return generator, */
  178. lua_pushvalue(L, 1); /* state, */
  179. lua_pushnil(L); /* and initial value */
  180. return 3;
  181. }
  182. static int luaB_ipairs (lua_State *L) {
  183. lua_Number i = lua_tonumber(L, 2);
  184. luaL_checktype(L, 1, LUA_TTABLE);
  185. if (i == 0 && lua_isnone(L, 2)) { /* `for' start? */
  186. lua_pushliteral(L, "ipairs");
  187. lua_rawget(L, LUA_GLOBALSINDEX); /* return generator, */
  188. lua_pushvalue(L, 1); /* state, */
  189. lua_pushnumber(L, 0); /* and initial value */
  190. return 3;
  191. }
  192. else { /* `for' step */
  193. i++; /* next value */
  194. lua_pushnumber(L, i);
  195. lua_rawgeti(L, 1, (int)i);
  196. return (lua_isnil(L, -1)) ? 0 : 2;
  197. }
  198. }
  199. static int passresults (lua_State *L, int status) {
  200. if (status == 0) return 1;
  201. else {
  202. lua_pushnil(L);
  203. lua_insert(L, -2);
  204. return 2;
  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 passresults(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. return passresults(L, luaL_loadfile(L, fname));
  216. }
  217. static int luaB_dofile (lua_State *L) {
  218. const char *fname = luaL_optstring(L, 1, NULL);
  219. int status = luaL_loadfile(L, fname);
  220. if (status != 0) lua_error(L);
  221. lua_call(L, 0, LUA_MULTRET);
  222. return lua_gettop(L) - 1;
  223. }
  224. static int luaB_assert (lua_State *L) {
  225. luaL_checkany(L, 1);
  226. if (!lua_toboolean(L, 1))
  227. return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
  228. lua_settop(L, 1);
  229. return 1;
  230. }
  231. static int luaB_unpack (lua_State *L) {
  232. int n, i;
  233. luaL_checktype(L, 1, LUA_TTABLE);
  234. lua_pushliteral(L, "n");
  235. lua_rawget(L, 1);
  236. n = (lua_isnumber(L, -1)) ? (int)lua_tonumber(L, -1) : -1;
  237. for (i=0; i<n || n==-1; i++) { /* push arg[1...n] */
  238. luaL_checkstack(L, LUA_MINSTACK, "table too big to unpack");
  239. lua_rawgeti(L, 1, i+1);
  240. if (n == -1) { /* no explicit limit? */
  241. if (lua_isnil(L, -1)) { /* stop at first `nil' element */
  242. lua_pop(L, 1); /* remove `nil' */
  243. break;
  244. }
  245. }
  246. }
  247. return i;
  248. }
  249. static int luaB_pcall (lua_State *L) {
  250. int status;
  251. luaL_checkany(L, 1);
  252. status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
  253. lua_pushboolean(L, (status == 0));
  254. lua_insert(L, 1);
  255. return lua_gettop(L); /* return status + all results */
  256. }
  257. static int luaB_xpcall (lua_State *L) {
  258. int status;
  259. luaL_checkany(L, 2);
  260. lua_settop(L, 2);
  261. lua_insert(L, 1); /* put error function under function to be called */
  262. status = lua_pcall(L, 0, LUA_MULTRET, 1);
  263. lua_pushboolean(L, (status == 0));
  264. lua_replace(L, 1);
  265. return lua_gettop(L); /* return status + all results */
  266. }
  267. static int luaB_tostring (lua_State *L) {
  268. char buff[64];
  269. luaL_checkany(L, 1);
  270. if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */
  271. return 1; /* use its value */
  272. switch (lua_type(L, 1)) {
  273. case LUA_TNUMBER:
  274. lua_pushstring(L, lua_tostring(L, 1));
  275. return 1;
  276. case LUA_TSTRING:
  277. lua_pushvalue(L, 1);
  278. return 1;
  279. case LUA_TBOOLEAN:
  280. lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
  281. return 1;
  282. case LUA_TTABLE:
  283. sprintf(buff, "table: %p", lua_topointer(L, 1));
  284. break;
  285. case LUA_TFUNCTION:
  286. sprintf(buff, "function: %p", lua_topointer(L, 1));
  287. break;
  288. case LUA_TUSERDATA:
  289. case LUA_TLIGHTUSERDATA:
  290. sprintf(buff, "userdata: %p", lua_touserdata(L, 1));
  291. break;
  292. case LUA_TTHREAD:
  293. sprintf(buff, "thread: %p", (void *)lua_tothread(L, 1));
  294. break;
  295. case LUA_TNIL:
  296. lua_pushliteral(L, "nil");
  297. return 1;
  298. }
  299. lua_pushstring(L, buff);
  300. return 1;
  301. }
  302. static int luaB_newproxy (lua_State *L) {
  303. lua_settop(L, 1);
  304. lua_newuserdata(L, 0); /* create proxy */
  305. if (lua_toboolean(L, 1) == 0)
  306. return 1; /* no metatable */
  307. else if (lua_isboolean(L, 1)) {
  308. lua_newtable(L); /* create a new metatable `m' ... */
  309. lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
  310. lua_pushboolean(L, 1);
  311. lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
  312. }
  313. else {
  314. int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
  315. if (lua_getmetatable(L, 1)) {
  316. lua_rawget(L, lua_upvalueindex(1));
  317. validproxy = lua_toboolean(L, -1);
  318. lua_pop(L, 1); /* remove value */
  319. }
  320. luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
  321. lua_getmetatable(L, 1); /* metatable is valid; get it */
  322. }
  323. lua_setmetatable(L, 2);
  324. return 1;
  325. }
  326. /*
  327. ** {======================================================
  328. ** `require' function
  329. ** =======================================================
  330. */
  331. /* name of global that holds table with loaded packages */
  332. #define REQTAB "_LOADED"
  333. /* name of global that holds the search path for packages */
  334. #define LUA_PATH "LUA_PATH"
  335. #ifndef LUA_PATH_SEP
  336. #define LUA_PATH_SEP ';'
  337. #endif
  338. #ifndef LUA_PATH_DEFAULT
  339. #define LUA_PATH_DEFAULT "?;?.lua"
  340. #endif
  341. static const char *getpath (lua_State *L) {
  342. const char *path;
  343. lua_getglobal(L, LUA_PATH); /* try global variable */
  344. path = lua_tostring(L, -1);
  345. lua_pop(L, 1);
  346. if (path) return path;
  347. path = getenv(LUA_PATH); /* else try environment variable */
  348. if (path) return path;
  349. return LUA_PATH_DEFAULT; /* else use default */
  350. }
  351. static const char *pushnextpath (lua_State *L, const char *path) {
  352. const char *l;
  353. if (*path == '\0') return NULL; /* no more paths */
  354. if (*path == LUA_PATH_SEP) path++; /* skip separator */
  355. l = strchr(path, LUA_PATH_SEP); /* find next separator */
  356. if (l == NULL) l = path+strlen(path);
  357. lua_pushlstring(L, path, l - path); /* directory name */
  358. return l;
  359. }
  360. static void pushcomposename (lua_State *L) {
  361. const char *path = lua_tostring(L, -1);
  362. const char *wild = strchr(path, '?');
  363. if (wild == NULL) return; /* no wild char; path is the file name */
  364. lua_pushlstring(L, path, wild - path);
  365. lua_pushvalue(L, 1); /* package name */
  366. lua_pushstring(L, wild + 1);
  367. lua_concat(L, 3);
  368. }
  369. static int luaB_require (lua_State *L) {
  370. const char *path;
  371. int status = LUA_ERRFILE; /* not found (yet) */
  372. luaL_checkstring(L, 1);
  373. lua_settop(L, 1);
  374. lua_pushvalue(L, 1);
  375. lua_setglobal(L, "_REQUIREDNAME");
  376. lua_getglobal(L, REQTAB);
  377. if (!lua_istable(L, 2)) return luaL_error(L, "`" REQTAB "' is not a table");
  378. path = getpath(L);
  379. lua_pushvalue(L, 1); /* check package's name in book-keeping table */
  380. lua_rawget(L, 2);
  381. if (!lua_isnil(L, -1)) /* is it there? */
  382. return 0; /* package is already loaded */
  383. else { /* must load it */
  384. while (status == LUA_ERRFILE) {
  385. lua_settop(L, 3); /* reset stack position */
  386. if ((path = pushnextpath(L, path)) == NULL) break;
  387. pushcomposename(L);
  388. status = luaL_loadfile(L, lua_tostring(L, -1)); /* try to load it */
  389. }
  390. }
  391. switch (status) {
  392. case 0: {
  393. lua_call(L, 0, 0); /* run loaded module */
  394. lua_pushvalue(L, 1);
  395. lua_pushboolean(L, 1);
  396. lua_rawset(L, 2); /* mark it as loaded */
  397. return 0;
  398. }
  399. case LUA_ERRFILE: { /* file not found */
  400. return luaL_error(L, "could not load package `%s' from path `%s'",
  401. lua_tostring(L, 1), getpath(L));
  402. }
  403. default: {
  404. return luaL_error(L, "error loading package\n%s", lua_tostring(L, -1));
  405. }
  406. }
  407. }
  408. /* }====================================================== */
  409. static const luaL_reg base_funcs[] = {
  410. {"error", luaB_error},
  411. {"getmetatable", luaB_getmetatable},
  412. {"setmetatable", luaB_setmetatable},
  413. {"getglobals", luaB_getglobals},
  414. {"setglobals", luaB_setglobals},
  415. {"next", luaB_next},
  416. {"ipairs", luaB_ipairs},
  417. {"pairs", luaB_pairs},
  418. {"print", luaB_print},
  419. {"tonumber", luaB_tonumber},
  420. {"tostring", luaB_tostring},
  421. {"type", luaB_type},
  422. {"assert", luaB_assert},
  423. {"unpack", luaB_unpack},
  424. {"rawequal", luaB_rawequal},
  425. {"rawget", luaB_rawget},
  426. {"rawset", luaB_rawset},
  427. {"pcall", luaB_pcall},
  428. {"xpcall", luaB_xpcall},
  429. {"collectgarbage", luaB_collectgarbage},
  430. {"gcinfo", luaB_gcinfo},
  431. {"loadfile", luaB_loadfile},
  432. {"dofile", luaB_dofile},
  433. {"loadstring", luaB_loadstring},
  434. {"require", luaB_require},
  435. {NULL, NULL}
  436. };
  437. /*
  438. ** {======================================================
  439. ** Coroutine library
  440. ** =======================================================
  441. */
  442. static int auxresume (lua_State *L, lua_State *co, int narg) {
  443. int status;
  444. if (!lua_checkstack(co, narg))
  445. luaL_error(L, "too many arguments to resume");
  446. lua_xmove(L, co, narg);
  447. status = lua_resume(co, narg);
  448. if (status == 0) {
  449. int nres = lua_gettop(co);
  450. if (!lua_checkstack(L, narg))
  451. luaL_error(L, "too many results to resume");
  452. lua_xmove(co, L, nres); /* move yielded values */
  453. return nres;
  454. }
  455. else {
  456. lua_xmove(co, L, 1); /* move error message */
  457. return -1; /* error flag */
  458. }
  459. }
  460. static int luaB_coresume (lua_State *L) {
  461. lua_State *co = lua_tothread(L, 1);
  462. int r;
  463. luaL_argcheck(L, co, 1, "coroutine expected");
  464. r = auxresume(L, co, lua_gettop(L) - 1);
  465. if (r < 0) {
  466. lua_pushboolean(L, 0);
  467. lua_insert(L, -2);
  468. return 2; /* return false + error message */
  469. }
  470. else {
  471. lua_pushboolean(L, 1);
  472. lua_insert(L, -(r + 1));
  473. return r + 1; /* return true + `resume' returns */
  474. }
  475. }
  476. static int luaB_auxwrap (lua_State *L) {
  477. lua_State *co = lua_tothread(L, lua_upvalueindex(1));
  478. int r = auxresume(L, co, lua_gettop(L));
  479. if (r < 0) lua_error(L); /* propagate error */
  480. return r;
  481. }
  482. static int luaB_cocreate (lua_State *L) {
  483. lua_State *NL = lua_newthread(L);
  484. luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
  485. "Lua function expected");
  486. lua_pushvalue(L, 1); /* move function to top */
  487. lua_xmove(L, NL, 1); /* move function from L to NL */
  488. return 1;
  489. }
  490. static int luaB_cowrap (lua_State *L) {
  491. luaB_cocreate(L);
  492. lua_pushcclosure(L, luaB_auxwrap, 1);
  493. return 1;
  494. }
  495. static int luaB_yield (lua_State *L) {
  496. return lua_yield(L, lua_gettop(L));
  497. }
  498. static int luaB_costatus (lua_State *L) {
  499. lua_State *co = lua_tothread(L, 1);
  500. luaL_argcheck(L, co, 1, "coroutine expected");
  501. if (L == co) lua_pushliteral(L, "running");
  502. else {
  503. lua_Debug ar;
  504. if (lua_getstack(co, 0, &ar) == 0 && lua_gettop(co) == 0)
  505. lua_pushliteral(L, "dead");
  506. else
  507. lua_pushliteral(L, "suspended");
  508. }
  509. return 1;
  510. }
  511. static const luaL_reg co_funcs[] = {
  512. {"create", luaB_cocreate},
  513. {"wrap", luaB_cowrap},
  514. {"resume", luaB_coresume},
  515. {"yield", luaB_yield},
  516. {"status", luaB_costatus},
  517. {NULL, NULL}
  518. };
  519. /* }====================================================== */
  520. static void base_open (lua_State *L) {
  521. lua_pushliteral(L, "_G");
  522. lua_pushvalue(L, LUA_GLOBALSINDEX);
  523. luaL_openlib(L, NULL, base_funcs, 0); /* open lib into global table */
  524. lua_pushliteral(L, "_VERSION");
  525. lua_pushliteral(L, LUA_VERSION);
  526. lua_rawset(L, -3); /* set global _VERSION */
  527. /* `newproxy' needs a weaktable as upvalue */
  528. lua_pushliteral(L, "newproxy");
  529. lua_newtable(L); /* new table `w' */
  530. lua_pushvalue(L, -1); /* `w' will be its own metatable */
  531. lua_setmetatable(L, -2);
  532. lua_pushliteral(L, "__mode");
  533. lua_pushliteral(L, "k");
  534. lua_rawset(L, -3); /* metatable(w).__mode = "k" */
  535. lua_pushcclosure(L, luaB_newproxy, 1);
  536. lua_rawset(L, -3); /* set global `newproxy' */
  537. lua_rawset(L, -1); /* set global _G */
  538. }
  539. LUALIB_API int lua_baselibopen (lua_State *L) {
  540. base_open(L);
  541. luaL_openlib(L, LUA_COLIBNAME, co_funcs, 0);
  542. lua_newtable(L);
  543. lua_setglobal(L, REQTAB);
  544. return 0;
  545. }