lbaselib.c 13 KB

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