lbaselib.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. ** $Id: lbaselib.c,v 1.292 2014/07/17 13:53:37 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 const char *b_str2int (const char *s, int base, lua_Integer *pn) {
  38. lua_Unsigned n = 0;
  39. int neg = 0;
  40. s += strspn(s, SPACECHARS); /* skip initial spaces */
  41. if (*s == '-') { s++; neg = 1; } /* handle signal */
  42. else if (*s == '+') s++;
  43. if (!isalnum((unsigned char)*s)) /* no digit? */
  44. return NULL;
  45. do {
  46. int digit = (isdigit((unsigned char)*s)) ? *s - '0'
  47. : toupper((unsigned char)*s) - 'A' + 10;
  48. if (digit >= base) return NULL; /* invalid numeral */
  49. n = n * base + digit;
  50. s++;
  51. } while (isalnum((unsigned char)*s));
  52. s += strspn(s, SPACECHARS); /* skip trailing spaces */
  53. if (*s != '\0') /* invalid trailing characters? */
  54. return NULL;
  55. *pn = (lua_Integer)((neg) ? (0u - n) : n);
  56. return s;
  57. }
  58. static int luaB_tonumber (lua_State *L) {
  59. if (lua_isnoneornil(L, 2)) { /* standard conversion? */
  60. luaL_checkany(L, 1);
  61. if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */
  62. lua_settop(L, 1); /* yes; return it */
  63. return 1;
  64. }
  65. else {
  66. size_t l;
  67. const char *s = lua_tolstring(L, 1, &l);
  68. if (s != NULL && lua_strtonum(L, s) == l + 1)
  69. return 1; /* successful conversion to number */
  70. /* else not a number */
  71. }
  72. }
  73. else {
  74. size_t l;
  75. const char *s;
  76. lua_Integer n = 0; /* to avoid warnings */
  77. int base = luaL_checkint(L, 2);
  78. luaL_checktype(L, 1, LUA_TSTRING); /* before 'luaL_checklstring'! */
  79. s = luaL_checklstring(L, 1, &l);
  80. luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
  81. if (b_str2int(s, base, &n) == s + l) {
  82. lua_pushinteger(L, n);
  83. return 1;
  84. } /* else not a number */
  85. } /* else not a number */
  86. lua_pushnil(L); /* not a number */
  87. return 1;
  88. }
  89. static int luaB_error (lua_State *L) {
  90. int level = luaL_optint(L, 2, 1);
  91. lua_settop(L, 1);
  92. if (lua_isstring(L, 1) && level > 0) { /* add extra information? */
  93. luaL_where(L, level);
  94. lua_pushvalue(L, 1);
  95. lua_concat(L, 2);
  96. }
  97. return lua_error(L);
  98. }
  99. static int luaB_getmetatable (lua_State *L) {
  100. luaL_checkany(L, 1);
  101. if (!lua_getmetatable(L, 1)) {
  102. lua_pushnil(L);
  103. return 1; /* no metatable */
  104. }
  105. luaL_getmetafield(L, 1, "__metatable");
  106. return 1; /* returns either __metatable field (if present) or metatable */
  107. }
  108. static int luaB_setmetatable (lua_State *L) {
  109. int t = lua_type(L, 2);
  110. luaL_checktype(L, 1, LUA_TTABLE);
  111. luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
  112. "nil or table expected");
  113. if (luaL_getmetafield(L, 1, "__metatable"))
  114. return luaL_error(L, "cannot change a protected metatable");
  115. lua_settop(L, 2);
  116. lua_setmetatable(L, 1);
  117. return 1;
  118. }
  119. static int luaB_rawequal (lua_State *L) {
  120. luaL_checkany(L, 1);
  121. luaL_checkany(L, 2);
  122. lua_pushboolean(L, lua_rawequal(L, 1, 2));
  123. return 1;
  124. }
  125. static int luaB_rawlen (lua_State *L) {
  126. int t = lua_type(L, 1);
  127. luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
  128. "table or string expected");
  129. lua_pushinteger(L, lua_rawlen(L, 1));
  130. return 1;
  131. }
  132. static int luaB_rawget (lua_State *L) {
  133. luaL_checktype(L, 1, LUA_TTABLE);
  134. luaL_checkany(L, 2);
  135. lua_settop(L, 2);
  136. lua_rawget(L, 1);
  137. return 1;
  138. }
  139. static int luaB_rawset (lua_State *L) {
  140. luaL_checktype(L, 1, LUA_TTABLE);
  141. luaL_checkany(L, 2);
  142. luaL_checkany(L, 3);
  143. lua_settop(L, 3);
  144. lua_rawset(L, 1);
  145. return 1;
  146. }
  147. static int luaB_collectgarbage (lua_State *L) {
  148. static const char *const opts[] = {"stop", "restart", "collect",
  149. "count", "step", "setpause", "setstepmul",
  150. "isrunning", NULL};
  151. static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
  152. LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
  153. LUA_GCISRUNNING};
  154. int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
  155. int ex = luaL_optint(L, 2, 0);
  156. int res = lua_gc(L, o, ex);
  157. switch (o) {
  158. case LUA_GCCOUNT: {
  159. int b = lua_gc(L, LUA_GCCOUNTB, 0);
  160. lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));
  161. return 1;
  162. }
  163. case LUA_GCSTEP: case LUA_GCISRUNNING: {
  164. lua_pushboolean(L, res);
  165. return 1;
  166. }
  167. default: {
  168. lua_pushinteger(L, res);
  169. return 1;
  170. }
  171. }
  172. }
  173. /*
  174. ** This function has all type names as upvalues, to maximize performance.
  175. */
  176. static int luaB_type (lua_State *L) {
  177. luaL_checkany(L, 1);
  178. lua_pushvalue(L, lua_upvalueindex(lua_type(L, 1) + 1));
  179. return 1;
  180. }
  181. static int pairsmeta (lua_State *L, const char *method, int iszero,
  182. lua_CFunction iter) {
  183. if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */
  184. luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */
  185. lua_pushcfunction(L, iter); /* 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, luaB_next);
  208. }
  209. /*
  210. ** Traversal function for 'ipairs' for raw tables
  211. */
  212. static int ipairsaux_raw (lua_State *L) {
  213. int i = luaL_checkint(L, 2) + 1;
  214. luaL_checktype(L, 1, LUA_TTABLE);
  215. lua_pushinteger(L, i);
  216. return (lua_rawgeti(L, 1, i) == LUA_TNIL) ? 1 : 2;
  217. }
  218. /*
  219. ** Traversal function for 'ipairs' for tables with metamethods
  220. */
  221. static int ipairsaux (lua_State *L) {
  222. int i = luaL_checkint(L, 2) + 1;
  223. if (i > luaL_len(L, 1)) { /* larger than length? */
  224. lua_pushnil(L); /* end traversal */
  225. return 1;
  226. }
  227. else {
  228. lua_pushinteger(L, i);
  229. lua_pushinteger(L, i); /* key for indexing table */
  230. lua_gettable(L, 1);
  231. return 2;
  232. }
  233. }
  234. /*
  235. ** This function will use either 'ipairsaux' or 'ipairsaux_raw' to
  236. ** traverse a table, depending on whether the table has metamethods
  237. ** that can affect the traversal.
  238. */
  239. static int luaB_ipairs (lua_State *L) {
  240. lua_CFunction iter =
  241. (luaL_getmetafield(L, 1, "__len") ||
  242. luaL_getmetafield(L, 1, "__index"))
  243. ? ipairsaux : ipairsaux_raw;
  244. #if defined(LUA_COMPAT_IPAIRS)
  245. return pairsmeta(L, "__ipairs", 1, iter);
  246. #else
  247. lua_pushcfunction(L, iter); /* iteration function */
  248. lua_pushvalue(L, 1); /* state */
  249. lua_pushinteger(L, 0); /* initial value */
  250. return 3;
  251. #endif
  252. }
  253. static int load_aux (lua_State *L, int status, int envidx) {
  254. if (status == LUA_OK) {
  255. if (envidx != 0) { /* 'env' parameter? */
  256. lua_pushvalue(L, envidx); /* environment for loaded function */
  257. if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */
  258. lua_pop(L, 1); /* remove 'env' if not used by previous call */
  259. }
  260. return 1;
  261. }
  262. else { /* error (message is on top of the stack) */
  263. lua_pushnil(L);
  264. lua_insert(L, -2); /* put before error message */
  265. return 2; /* return nil plus error message */
  266. }
  267. }
  268. static int luaB_loadfile (lua_State *L) {
  269. const char *fname = luaL_optstring(L, 1, NULL);
  270. const char *mode = luaL_optstring(L, 2, NULL);
  271. int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */
  272. int status = luaL_loadfilex(L, fname, mode);
  273. return load_aux(L, status, env);
  274. }
  275. /*
  276. ** {======================================================
  277. ** Generic Read function
  278. ** =======================================================
  279. */
  280. /*
  281. ** reserved slot, above all arguments, to hold a copy of the returned
  282. ** string to avoid it being collected while parsed. 'load' has four
  283. ** optional arguments (chunk, source name, mode, and environment).
  284. */
  285. #define RESERVEDSLOT 5
  286. /*
  287. ** Reader for generic `load' function: `lua_load' uses the
  288. ** stack for internal stuff, so the reader cannot change the
  289. ** stack top. Instead, it keeps its resulting string in a
  290. ** reserved slot inside the stack.
  291. */
  292. static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
  293. (void)(ud); /* not used */
  294. luaL_checkstack(L, 2, "too many nested functions");
  295. lua_pushvalue(L, 1); /* get function */
  296. lua_call(L, 0, 1); /* call it */
  297. if (lua_isnil(L, -1)) {
  298. lua_pop(L, 1); /* pop result */
  299. *size = 0;
  300. return NULL;
  301. }
  302. else if (!lua_isstring(L, -1))
  303. luaL_error(L, "reader function must return a string");
  304. lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
  305. return lua_tolstring(L, RESERVEDSLOT, size);
  306. }
  307. static int luaB_load (lua_State *L) {
  308. int status;
  309. size_t l;
  310. const char *s = lua_tolstring(L, 1, &l);
  311. const char *mode = luaL_optstring(L, 3, "bt");
  312. int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */
  313. if (s != NULL) { /* loading a string? */
  314. const char *chunkname = luaL_optstring(L, 2, s);
  315. status = luaL_loadbufferx(L, s, l, chunkname, mode);
  316. }
  317. else { /* loading from a reader function */
  318. const char *chunkname = luaL_optstring(L, 2, "=(load)");
  319. luaL_checktype(L, 1, LUA_TFUNCTION);
  320. lua_settop(L, RESERVEDSLOT); /* create reserved slot */
  321. status = lua_load(L, generic_reader, NULL, chunkname, mode);
  322. }
  323. return load_aux(L, status, env);
  324. }
  325. /* }====================================================== */
  326. static int dofilecont (lua_State *L, int d1, lua_Ctx d2) {
  327. (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */
  328. return lua_gettop(L) - 1;
  329. }
  330. static int luaB_dofile (lua_State *L) {
  331. const char *fname = luaL_optstring(L, 1, NULL);
  332. lua_settop(L, 1);
  333. if (luaL_loadfile(L, fname) != LUA_OK)
  334. return lua_error(L);
  335. lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
  336. return dofilecont(L, 0, 0);
  337. }
  338. static int luaB_assert (lua_State *L) {
  339. if (lua_toboolean(L, 1)) /* condition is true? */
  340. return lua_gettop(L); /* return all arguments */
  341. else { /* error */
  342. if (lua_isnone(L, 2)) /* no error message? */
  343. lua_pushliteral(L, "assertion failed!"); /* use standard message */
  344. lua_remove(L, 1); /* remove the condition (if there is one...) */
  345. return luaB_error(L); /* call 'error' */
  346. }
  347. }
  348. static int luaB_select (lua_State *L) {
  349. int n = lua_gettop(L);
  350. if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
  351. lua_pushinteger(L, n-1);
  352. return 1;
  353. }
  354. else {
  355. int i = luaL_checkint(L, 1);
  356. if (i < 0) i = n + i;
  357. else if (i > n) i = n;
  358. luaL_argcheck(L, 1 <= i, 1, "index out of range");
  359. return n - i;
  360. }
  361. }
  362. /*
  363. ** Continuation function for 'pcall' and 'xpcall'. Both functions
  364. ** already pushed a 'true' before doing the call, so in case of success
  365. ** 'finishpcall' only has to return everything in the stack minus
  366. ** 'extra' values (where 'extra' is exactly the number of items to be
  367. ** ignored).
  368. */
  369. static int finishpcall (lua_State *L, int status, lua_Ctx extra) {
  370. if (status != LUA_OK && status != LUA_YIELD) { /* error? */
  371. lua_pushboolean(L, 0); /* first result (false) */
  372. lua_pushvalue(L, -2); /* error message */
  373. return 2; /* return false, msg */
  374. }
  375. else
  376. return lua_gettop(L) - extra; /* return all results */
  377. }
  378. static int luaB_pcall (lua_State *L) {
  379. int status;
  380. luaL_checkany(L, 1);
  381. lua_pushboolean(L, 1); /* first result if no errors */
  382. lua_insert(L, 1); /* put it in place */
  383. status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
  384. return finishpcall(L, status, 0);
  385. }
  386. /*
  387. ** Do a protected call with error handling. After 'lua_rotate', the
  388. ** stack will have <f, err, true, f, [args...]>; so, the function passes
  389. ** 2 to 'finishpcall' to skip the 2 first values when returning results.
  390. */
  391. static int luaB_xpcall (lua_State *L) {
  392. int status;
  393. int n = lua_gettop(L);
  394. luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */
  395. lua_pushboolean(L, 1); /* first result */
  396. lua_pushvalue(L, 1); /* function */
  397. lua_rotate(L, 3, 2); /* move them below function's arguments */
  398. status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
  399. return finishpcall(L, status, 2);
  400. }
  401. static int luaB_tostring (lua_State *L) {
  402. luaL_checkany(L, 1);
  403. luaL_tolstring(L, 1, NULL);
  404. return 1;
  405. }
  406. static const luaL_Reg base_funcs[] = {
  407. {"assert", luaB_assert},
  408. {"collectgarbage", luaB_collectgarbage},
  409. {"dofile", luaB_dofile},
  410. {"error", luaB_error},
  411. {"getmetatable", luaB_getmetatable},
  412. {"ipairs", luaB_ipairs},
  413. {"loadfile", luaB_loadfile},
  414. {"load", luaB_load},
  415. #if defined(LUA_COMPAT_LOADSTRING)
  416. {"loadstring", luaB_load},
  417. #endif
  418. {"next", luaB_next},
  419. {"pairs", luaB_pairs},
  420. {"pcall", luaB_pcall},
  421. {"print", luaB_print},
  422. {"rawequal", luaB_rawequal},
  423. {"rawlen", luaB_rawlen},
  424. {"rawget", luaB_rawget},
  425. {"rawset", luaB_rawset},
  426. {"select", luaB_select},
  427. {"setmetatable", luaB_setmetatable},
  428. {"tonumber", luaB_tonumber},
  429. {"tostring", luaB_tostring},
  430. {"xpcall", luaB_xpcall},
  431. /* placeholders */
  432. {"type", NULL},
  433. {"_G", NULL},
  434. {"_VERSION", NULL},
  435. {NULL, NULL}
  436. };
  437. LUAMOD_API int luaopen_base (lua_State *L) {
  438. int i;
  439. /* open lib into global table */
  440. lua_pushglobaltable(L);
  441. luaL_setfuncs(L, base_funcs, 0);
  442. /* set global _G */
  443. lua_pushvalue(L, -1);
  444. lua_setfield(L, -2, "_G");
  445. /* set global _VERSION */
  446. lua_pushliteral(L, LUA_VERSION);
  447. lua_setfield(L, -2, "_VERSION");
  448. /* set function 'type' with proper upvalues */
  449. for (i = 0; i < LUA_NUMTAGS; i++) /* push all type names as upvalues */
  450. lua_pushstring(L, lua_typename(L, i));
  451. lua_pushcclosure(L, luaB_type, LUA_NUMTAGS);
  452. lua_setfield(L, -2, "type");
  453. return 1;
  454. }