lbaselib.c 13 KB

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