lbaselib.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /*
  2. ** $Id: lbaselib.c,v 1.250 2010/09/07 19:38:36 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. static int luaB_print (lua_State *L) {
  16. int n = lua_gettop(L); /* number of arguments */
  17. int i;
  18. lua_getglobal(L, "tostring");
  19. for (i=1; i<=n; i++) {
  20. const char *s;
  21. size_t l;
  22. lua_pushvalue(L, -1); /* function to be called */
  23. lua_pushvalue(L, i); /* value to print */
  24. lua_call(L, 1, 1);
  25. s = lua_tolstring(L, -1, &l); /* get result */
  26. if (s == NULL)
  27. return luaL_error(L, LUA_QL("tostring") " must return a string to "
  28. LUA_QL("print"));
  29. if (i>1) luai_writestring("\t", 1);
  30. luai_writestring(s, l);
  31. lua_pop(L, 1); /* pop result */
  32. }
  33. luai_writestring("\n", 1);
  34. return 0;
  35. }
  36. static int luaB_tonumber (lua_State *L) {
  37. int base = luaL_optint(L, 2, 10);
  38. if (base == 10) { /* standard conversion */
  39. luaL_checkany(L, 1);
  40. if (lua_isnumber(L, 1)) {
  41. lua_pushnumber(L, lua_tonumber(L, 1));
  42. return 1;
  43. }
  44. }
  45. else {
  46. const char *s1 = luaL_checkstring(L, 1);
  47. char *s2;
  48. unsigned long n;
  49. int neg = 0;
  50. luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
  51. while (isspace((unsigned char)(*s1))) s1++; /* skip initial spaces */
  52. if (*s1 == '-') { s1++; neg = 1; }
  53. n = strtoul(s1, &s2, base);
  54. if (s1 != s2) { /* at least one valid digit? */
  55. while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */
  56. if (*s2 == '\0') { /* no invalid trailing characters? */
  57. lua_pushnumber(L, (neg) ? -(lua_Number)n : (lua_Number)n);
  58. return 1;
  59. }
  60. }
  61. }
  62. lua_pushnil(L); /* else not a number */
  63. return 1;
  64. }
  65. static int luaB_error (lua_State *L) {
  66. int level = luaL_optint(L, 2, 1);
  67. lua_settop(L, 1);
  68. if (lua_isstring(L, 1) && level > 0) { /* add extra information? */
  69. luaL_where(L, level);
  70. lua_pushvalue(L, 1);
  71. lua_concat(L, 2);
  72. }
  73. return lua_error(L);
  74. }
  75. static int luaB_getmetatable (lua_State *L) {
  76. luaL_checkany(L, 1);
  77. if (!lua_getmetatable(L, 1)) {
  78. lua_pushnil(L);
  79. return 1; /* no metatable */
  80. }
  81. luaL_getmetafield(L, 1, "__metatable");
  82. return 1; /* returns either __metatable field (if present) or metatable */
  83. }
  84. static int luaB_setmetatable (lua_State *L) {
  85. int t = lua_type(L, 2);
  86. luaL_checktype(L, 1, LUA_TTABLE);
  87. luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
  88. "nil or table expected");
  89. if (luaL_getmetafield(L, 1, "__metatable"))
  90. return luaL_error(L, "cannot change a protected metatable");
  91. lua_settop(L, 2);
  92. lua_setmetatable(L, 1);
  93. return 1;
  94. }
  95. static int luaB_getfenv (lua_State *L) {
  96. return luaL_error(L, "getfenv/setfenv deprecated");
  97. }
  98. #define luaB_setfenv luaB_getfenv
  99. static int luaB_rawequal (lua_State *L) {
  100. luaL_checkany(L, 1);
  101. luaL_checkany(L, 2);
  102. lua_pushboolean(L, lua_rawequal(L, 1, 2));
  103. return 1;
  104. }
  105. static int luaB_rawget (lua_State *L) {
  106. luaL_checktype(L, 1, LUA_TTABLE);
  107. luaL_checkany(L, 2);
  108. lua_settop(L, 2);
  109. lua_rawget(L, 1);
  110. return 1;
  111. }
  112. static int luaB_rawset (lua_State *L) {
  113. luaL_checktype(L, 1, LUA_TTABLE);
  114. luaL_checkany(L, 2);
  115. luaL_checkany(L, 3);
  116. lua_settop(L, 3);
  117. lua_rawset(L, 1);
  118. return 1;
  119. }
  120. static int luaB_collectgarbage (lua_State *L) {
  121. static const char *const opts[] = {"stop", "restart", "collect",
  122. "count", "step", "setpause", "setstepmul",
  123. "setmajorinc", "isrunning", "gen", "inc", NULL};
  124. static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
  125. LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
  126. LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
  127. int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
  128. int ex = luaL_optint(L, 2, 0);
  129. int res = lua_gc(L, o, ex);
  130. switch (o) {
  131. case LUA_GCCOUNT: {
  132. int b = lua_gc(L, LUA_GCCOUNTB, 0);
  133. lua_pushnumber(L, res + ((lua_Number)b/1024));
  134. lua_pushinteger(L, b);
  135. return 2;
  136. }
  137. case LUA_GCSTEP: case LUA_GCISRUNNING: {
  138. lua_pushboolean(L, res);
  139. return 1;
  140. }
  141. default: {
  142. lua_pushinteger(L, res);
  143. return 1;
  144. }
  145. }
  146. }
  147. static int luaB_type (lua_State *L) {
  148. luaL_checkany(L, 1);
  149. lua_pushstring(L, luaL_typename(L, 1));
  150. return 1;
  151. }
  152. static int pairsmeta (lua_State *L, const char *method, int iszero,
  153. lua_CFunction iter) {
  154. if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */
  155. luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */
  156. lua_pushcfunction(L, iter); /* will return generator, */
  157. lua_pushvalue(L, 1); /* state, */
  158. if (iszero) lua_pushinteger(L, 0); /* and initial value */
  159. else lua_pushnil(L);
  160. }
  161. else {
  162. lua_pushvalue(L, 1); /* argument 'self' to metamethod */
  163. lua_call(L, 1, 3); /* get 3 values from metamethod */
  164. }
  165. return 3;
  166. }
  167. static int luaB_next (lua_State *L) {
  168. luaL_checktype(L, 1, LUA_TTABLE);
  169. lua_settop(L, 2); /* create a 2nd argument if there isn't one */
  170. if (lua_next(L, 1))
  171. return 2;
  172. else {
  173. lua_pushnil(L);
  174. return 1;
  175. }
  176. }
  177. static int luaB_pairs (lua_State *L) {
  178. return pairsmeta(L, "__pairs", 0, luaB_next);
  179. }
  180. static int ipairsaux (lua_State *L) {
  181. int i = luaL_checkint(L, 2);
  182. luaL_checktype(L, 1, LUA_TTABLE);
  183. i++; /* next value */
  184. lua_pushinteger(L, i);
  185. lua_rawgeti(L, 1, i);
  186. return (lua_isnil(L, -1)) ? 1 : 2;
  187. }
  188. static int luaB_ipairs (lua_State *L) {
  189. return pairsmeta(L, "__ipairs", 1, ipairsaux);
  190. }
  191. static int load_aux (lua_State *L, int status) {
  192. if (status == LUA_OK)
  193. return 1;
  194. else {
  195. lua_pushnil(L);
  196. lua_insert(L, -2); /* put before error message */
  197. return 2; /* return nil plus error message */
  198. }
  199. }
  200. static int luaB_loadfile (lua_State *L) {
  201. const char *fname = luaL_optstring(L, 1, NULL);
  202. return load_aux(L, luaL_loadfile(L, fname));
  203. }
  204. /*
  205. ** {======================================================
  206. ** Generic Read function
  207. ** =======================================================
  208. */
  209. static const char *checkrights (lua_State *L, const char *mode, const char *s) {
  210. if (strchr(mode, 'b') == NULL && *s == LUA_SIGNATURE[0])
  211. return lua_pushstring(L, "attempt to load a binary chunk");
  212. if (strchr(mode, 't') == NULL && *s != LUA_SIGNATURE[0])
  213. return lua_pushstring(L, "attempt to load a text chunk");
  214. return NULL; /* chunk in allowed format */
  215. }
  216. /*
  217. ** reserves a slot, above all arguments, to hold a copy of the returned
  218. ** string to avoid it being collected while parsed
  219. */
  220. #define RESERVEDSLOT 4
  221. /*
  222. ** Reader for generic `load' function: `lua_load' uses the
  223. ** stack for internal stuff, so the reader cannot change the
  224. ** stack top. Instead, it keeps its resulting string in a
  225. ** reserved slot inside the stack.
  226. */
  227. typedef struct { /* reader state */
  228. int f; /* position of reader function on stack */
  229. const char *mode; /* allowed modes (binary/text) */
  230. } Readstat;
  231. static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
  232. const char *s;
  233. Readstat *stat = (Readstat *)ud;
  234. luaL_checkstack(L, 2, "too many nested functions");
  235. lua_pushvalue(L, stat->f); /* get function */
  236. lua_call(L, 0, 1); /* call it */
  237. if (lua_isnil(L, -1)) {
  238. *size = 0;
  239. return NULL;
  240. }
  241. else if ((s = lua_tostring(L, -1)) != NULL) {
  242. if (stat->mode != NULL) { /* first time? */
  243. s = checkrights(L, stat->mode, s); /* check mode */
  244. stat->mode = NULL; /* to avoid further checks */
  245. if (s) luaL_error(L, s);
  246. }
  247. lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
  248. return lua_tolstring(L, RESERVEDSLOT, size);
  249. }
  250. else {
  251. luaL_error(L, "reader function must return a string");
  252. return NULL; /* to avoid warnings */
  253. }
  254. }
  255. static int luaB_load_aux (lua_State *L, int farg) {
  256. int status;
  257. Readstat stat;
  258. size_t l;
  259. const char *s = lua_tolstring(L, farg, &l);
  260. stat.mode = luaL_optstring(L, farg + 2, "bt");
  261. if (s != NULL) { /* loading a string? */
  262. const char *chunkname = luaL_optstring(L, farg + 1, s);
  263. status = (checkrights(L, stat.mode, s) != NULL)
  264. || luaL_loadbuffer(L, s, l, chunkname);
  265. }
  266. else { /* loading from a reader function */
  267. const char *chunkname = luaL_optstring(L, farg + 1, "=(load)");
  268. luaL_checktype(L, farg, LUA_TFUNCTION);
  269. stat.f = farg;
  270. lua_settop(L, RESERVEDSLOT); /* create reserved slot */
  271. status = lua_load(L, generic_reader, &stat, chunkname);
  272. }
  273. return load_aux(L, status);
  274. }
  275. static int luaB_load (lua_State *L) {
  276. return luaB_load_aux(L, 1);
  277. }
  278. static int luaB_loadin (lua_State *L) {
  279. int n;
  280. luaL_checkany(L, 1);
  281. n = luaB_load_aux(L, 2);
  282. if (n == 1) { /* success? */
  283. lua_pushvalue(L, 1); /* environment for loaded function */
  284. if (lua_setupvalue(L, -2, 1) == NULL)
  285. luaL_error(L, "loaded chunk does not have an upvalue");
  286. }
  287. return n;
  288. }
  289. static int luaB_loadstring (lua_State *L) {
  290. lua_settop(L, 2);
  291. lua_pushliteral(L, "tb");
  292. return luaB_load(L); /* dostring(s, n) == load(s, n, "tb") */
  293. }
  294. /* }====================================================== */
  295. static int dofilecont (lua_State *L) {
  296. return lua_gettop(L) - 1;
  297. }
  298. static int luaB_dofile (lua_State *L) {
  299. const char *fname = luaL_optstring(L, 1, NULL);
  300. lua_settop(L, 1);
  301. if (luaL_loadfile(L, fname) != LUA_OK) lua_error(L);
  302. lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
  303. return dofilecont(L);
  304. }
  305. static int luaB_assert (lua_State *L) {
  306. if (!lua_toboolean(L, 1))
  307. return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
  308. return lua_gettop(L);
  309. }
  310. static int luaB_select (lua_State *L) {
  311. int n = lua_gettop(L);
  312. if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
  313. lua_pushinteger(L, n-1);
  314. return 1;
  315. }
  316. else {
  317. int i = luaL_checkint(L, 1);
  318. if (i < 0) i = n + i;
  319. else if (i > n) i = n;
  320. luaL_argcheck(L, 1 <= i, 1, "index out of range");
  321. return n - i;
  322. }
  323. }
  324. static int pcallcont (lua_State *L) {
  325. int errfunc; /* call has an error function in bottom of the stack */
  326. int status = lua_getctx(L, &errfunc);
  327. lua_assert(status != LUA_OK);
  328. lua_pushboolean(L, (status == LUA_YIELD)); /* first result (status) */
  329. if (errfunc) /* came from xpcall? */
  330. lua_replace(L, 1); /* put first result in place of error function */
  331. else /* came from pcall */
  332. lua_insert(L, 1); /* open space for first result */
  333. return lua_gettop(L);
  334. }
  335. static int luaB_pcall (lua_State *L) {
  336. int status;
  337. luaL_checkany(L, 1);
  338. status = lua_pcallk(L, lua_gettop(L) - 1, LUA_MULTRET, 0, 0, pcallcont);
  339. luaL_checkstack(L, 1, NULL);
  340. lua_pushboolean(L, (status == LUA_OK));
  341. lua_insert(L, 1);
  342. return lua_gettop(L); /* return status + all results */
  343. }
  344. static int luaB_xpcall (lua_State *L) {
  345. int status;
  346. int n = lua_gettop(L);
  347. luaL_argcheck(L, n >= 2, 2, "value expected");
  348. lua_pushvalue(L, 1); /* exchange function... */
  349. lua_copy(L, 2, 1); /* ...and error handler */
  350. lua_replace(L, 2);
  351. status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 1, pcallcont);
  352. luaL_checkstack(L, 1, NULL);
  353. lua_pushboolean(L, (status == LUA_OK));
  354. lua_replace(L, 1);
  355. return lua_gettop(L); /* return status + all results */
  356. }
  357. static int luaB_tostring (lua_State *L) {
  358. luaL_checkany(L, 1);
  359. luaL_tolstring(L, 1, NULL);
  360. return 1;
  361. }
  362. static int luaB_newproxy (lua_State *L) {
  363. lua_settop(L, 1);
  364. lua_newuserdata(L, 0); /* create proxy */
  365. if (lua_toboolean(L, 1) == 0)
  366. return 1; /* no metatable */
  367. else if (lua_isboolean(L, 1)) {
  368. lua_createtable(L, 0, 1); /* create a new metatable `m' ... */
  369. lua_pushboolean(L, 1);
  370. lua_setfield(L, -2, "__gc"); /* ... m.__gc = false (HACK!!)... */
  371. lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
  372. lua_pushboolean(L, 1);
  373. lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
  374. }
  375. else {
  376. int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
  377. if (lua_getmetatable(L, 1)) {
  378. lua_rawget(L, lua_upvalueindex(1));
  379. validproxy = lua_toboolean(L, -1);
  380. lua_pop(L, 1); /* remove value */
  381. }
  382. luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
  383. lua_getmetatable(L, 1); /* metatable is valid; get it */
  384. }
  385. lua_setmetatable(L, 2);
  386. return 1;
  387. }
  388. static const luaL_Reg base_funcs[] = {
  389. {"assert", luaB_assert},
  390. {"collectgarbage", luaB_collectgarbage},
  391. {"dofile", luaB_dofile},
  392. {"error", luaB_error},
  393. {"getfenv", luaB_getfenv},
  394. {"getmetatable", luaB_getmetatable},
  395. {"ipairs", luaB_ipairs},
  396. {"loadfile", luaB_loadfile},
  397. {"load", luaB_load},
  398. {"loadin", luaB_loadin},
  399. {"loadstring", luaB_loadstring},
  400. {"next", luaB_next},
  401. {"pairs", luaB_pairs},
  402. {"pcall", luaB_pcall},
  403. {"print", luaB_print},
  404. {"rawequal", luaB_rawequal},
  405. {"rawget", luaB_rawget},
  406. {"rawset", luaB_rawset},
  407. {"select", luaB_select},
  408. {"setfenv", luaB_setfenv},
  409. {"setmetatable", luaB_setmetatable},
  410. {"tonumber", luaB_tonumber},
  411. {"tostring", luaB_tostring},
  412. {"type", luaB_type},
  413. {"xpcall", luaB_xpcall},
  414. {NULL, NULL}
  415. };
  416. LUAMOD_API int luaopen_base (lua_State *L) {
  417. /* set global _G */
  418. lua_pushglobaltable(L);
  419. lua_pushglobaltable(L);
  420. lua_setfield(L, -2, "_G");
  421. /* open lib into global table */
  422. luaL_setfuncs(L, base_funcs, 0);
  423. lua_pushliteral(L, LUA_VERSION);
  424. lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */
  425. /* `newproxy' needs a weaktable as upvalue */
  426. lua_createtable(L, 0, 1); /* new table `w' */
  427. lua_pushvalue(L, -1); /* `w' will be its own metatable */
  428. lua_setmetatable(L, -2);
  429. lua_pushliteral(L, "kv");
  430. lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
  431. lua_pushcclosure(L, luaB_newproxy, 1);
  432. lua_setfield(L, -2, "newproxy"); /* set global `newproxy' */
  433. return 1;
  434. }