lbaselib.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /*
  2. ** $Id: lbaselib.c $
  3. ** Basic library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lbaselib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <ctype.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include "lua.h"
  14. #include "lauxlib.h"
  15. #include "lualib.h"
  16. static int luaB_print (lua_State *L) {
  17. int n = lua_gettop(L); /* number of arguments */
  18. int i;
  19. for (i = 1; i <= n; i++) { /* for each argument */
  20. size_t l;
  21. const char *s = luaL_tolstring(L, i, &l); /* convert it to string */
  22. if (i > 1) /* not the first element? */
  23. lua_writestring("\t", 1); /* add a tab before it */
  24. lua_writestring(s, l); /* print it */
  25. lua_pop(L, 1); /* pop result */
  26. }
  27. lua_writeline();
  28. return 0;
  29. }
  30. /*
  31. ** Creates a warning with all given arguments.
  32. ** Check first for errors; otherwise an error may interrupt
  33. ** the composition of a warning, leaving it unfinished.
  34. */
  35. static int luaB_warn (lua_State *L) {
  36. int n = lua_gettop(L); /* number of arguments */
  37. int i;
  38. luaL_checkstring(L, 1); /* at least one argument */
  39. for (i = 2; i <= n; i++)
  40. luaL_checkstring(L, i); /* make sure all arguments are strings */
  41. for (i = 1; i < n; i++) /* compose warning */
  42. lua_warning(L, lua_tostring(L, i), 1);
  43. lua_warning(L, lua_tostring(L, n), 0); /* close warning */
  44. return 0;
  45. }
  46. #define SPACECHARS " \f\n\r\t\v"
  47. static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
  48. lua_Unsigned n = 0;
  49. int neg = 0;
  50. s += strspn(s, SPACECHARS); /* skip initial spaces */
  51. if (*s == '-') { s++; neg = 1; } /* handle sign */
  52. else if (*s == '+') s++;
  53. if (!isalnum((unsigned char)*s)) /* no digit? */
  54. return NULL;
  55. do {
  56. int digit = (isdigit((unsigned char)*s)) ? *s - '0'
  57. : (toupper((unsigned char)*s) - 'A') + 10;
  58. if (digit >= base) return NULL; /* invalid numeral */
  59. n = n * base + digit;
  60. s++;
  61. } while (isalnum((unsigned char)*s));
  62. s += strspn(s, SPACECHARS); /* skip trailing spaces */
  63. *pn = (lua_Integer)((neg) ? (0u - n) : n);
  64. return s;
  65. }
  66. static int luaB_tonumber (lua_State *L) {
  67. if (lua_isnoneornil(L, 2)) { /* standard conversion? */
  68. if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */
  69. lua_settop(L, 1); /* yes; return it */
  70. return 1;
  71. }
  72. else {
  73. size_t l;
  74. const char *s = lua_tolstring(L, 1, &l);
  75. if (s != NULL && lua_stringtonumber(L, s) == l + 1)
  76. return 1; /* successful conversion to number */
  77. /* else not a number */
  78. luaL_checkany(L, 1); /* (but there must be some parameter) */
  79. }
  80. }
  81. else {
  82. size_t l;
  83. const char *s;
  84. lua_Integer n = 0; /* to avoid warnings */
  85. lua_Integer base = luaL_checkinteger(L, 2);
  86. luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */
  87. s = lua_tolstring(L, 1, &l);
  88. luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
  89. if (b_str2int(s, (int)base, &n) == s + l) {
  90. lua_pushinteger(L, n);
  91. return 1;
  92. } /* else not a number */
  93. } /* else not a number */
  94. luaL_pushfail(L); /* not a number */
  95. return 1;
  96. }
  97. static int luaB_error (lua_State *L) {
  98. int level = (int)luaL_optinteger(L, 2, 1);
  99. lua_settop(L, 1);
  100. if (lua_type(L, 1) == LUA_TSTRING && level > 0) {
  101. luaL_where(L, level); /* add extra information */
  102. lua_pushvalue(L, 1);
  103. lua_concat(L, 2);
  104. }
  105. return lua_error(L);
  106. }
  107. static int luaB_getmetatable (lua_State *L) {
  108. luaL_checkany(L, 1);
  109. if (!lua_getmetatable(L, 1)) {
  110. lua_pushnil(L);
  111. return 1; /* no metatable */
  112. }
  113. luaL_getmetafield(L, 1, "__metatable");
  114. return 1; /* returns either __metatable field (if present) or metatable */
  115. }
  116. static int luaB_setmetatable (lua_State *L) {
  117. int t = lua_type(L, 2);
  118. luaL_checktype(L, 1, LUA_TTABLE);
  119. luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table");
  120. if (l_unlikely(luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL))
  121. return luaL_error(L, "cannot change a protected metatable");
  122. lua_settop(L, 2);
  123. lua_setmetatable(L, 1);
  124. return 1;
  125. }
  126. static int luaB_rawequal (lua_State *L) {
  127. luaL_checkany(L, 1);
  128. luaL_checkany(L, 2);
  129. lua_pushboolean(L, lua_rawequal(L, 1, 2));
  130. return 1;
  131. }
  132. static int luaB_rawlen (lua_State *L) {
  133. int t = lua_type(L, 1);
  134. luaL_argexpected(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
  135. "table or string");
  136. lua_pushinteger(L, lua_rawlen(L, 1));
  137. return 1;
  138. }
  139. static int luaB_rawget (lua_State *L) {
  140. luaL_checktype(L, 1, LUA_TTABLE);
  141. luaL_checkany(L, 2);
  142. lua_settop(L, 2);
  143. lua_rawget(L, 1);
  144. return 1;
  145. }
  146. static int luaB_rawset (lua_State *L) {
  147. luaL_checktype(L, 1, LUA_TTABLE);
  148. luaL_checkany(L, 2);
  149. luaL_checkany(L, 3);
  150. lua_settop(L, 3);
  151. lua_rawset(L, 1);
  152. return 1;
  153. }
  154. static int pushmode (lua_State *L, int oldmode) {
  155. if (oldmode == -1)
  156. luaL_pushfail(L); /* invalid call to 'lua_gc' */
  157. else
  158. lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental"
  159. : "generational");
  160. return 1;
  161. }
  162. /*
  163. ** check whether call to 'lua_gc' was valid (not inside a finalizer)
  164. */
  165. #define checkvalres(res) { if (res == -1) break; }
  166. static int luaB_collectgarbage (lua_State *L) {
  167. static const char *const opts[] = {"stop", "restart", "collect",
  168. "count", "step", "isrunning", "generational", "incremental",
  169. "param", NULL};
  170. static const char optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
  171. LUA_GCCOUNT, LUA_GCSTEP, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC,
  172. LUA_GCPARAM};
  173. int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
  174. switch (o) {
  175. case LUA_GCCOUNT: {
  176. int k = lua_gc(L, o);
  177. int b = lua_gc(L, LUA_GCCOUNTB);
  178. checkvalres(k);
  179. lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024));
  180. return 1;
  181. }
  182. case LUA_GCSTEP: {
  183. lua_Integer n = luaL_optinteger(L, 2, 0);
  184. int res = lua_gc(L, o, (int)n);
  185. checkvalres(res);
  186. lua_pushboolean(L, res);
  187. return 1;
  188. }
  189. case LUA_GCISRUNNING: {
  190. int res = lua_gc(L, o);
  191. checkvalres(res);
  192. lua_pushboolean(L, res);
  193. return 1;
  194. }
  195. case LUA_GCGEN: {
  196. return pushmode(L, lua_gc(L, o));
  197. }
  198. case LUA_GCINC: {
  199. return pushmode(L, lua_gc(L, o));
  200. }
  201. case LUA_GCPARAM: {
  202. static const char *const params[] = {
  203. "minormul", "majorminor", "minormajor",
  204. "pause", "stepmul", "stepsize", NULL};
  205. static const char pnum[] = {
  206. LUA_GCPMINORMUL, LUA_GCPMAJORMINOR, LUA_GCPMINORMAJOR,
  207. LUA_GCPPAUSE, LUA_GCPSTEPMUL, LUA_GCPSTEPSIZE};
  208. int p = pnum[luaL_checkoption(L, 2, NULL, params)];
  209. lua_Integer value = luaL_optinteger(L, 3, -1);
  210. lua_pushinteger(L, lua_gc(L, o, p, (int)value));
  211. return 1;
  212. }
  213. default: {
  214. int res = lua_gc(L, o);
  215. checkvalres(res);
  216. lua_pushinteger(L, res);
  217. return 1;
  218. }
  219. }
  220. luaL_pushfail(L); /* invalid call (inside a finalizer) */
  221. return 1;
  222. }
  223. static int luaB_type (lua_State *L) {
  224. int t = lua_type(L, 1);
  225. luaL_argcheck(L, t != LUA_TNONE, 1, "value expected");
  226. lua_pushstring(L, lua_typename(L, t));
  227. return 1;
  228. }
  229. static int luaB_next (lua_State *L) {
  230. luaL_checktype(L, 1, LUA_TTABLE);
  231. lua_settop(L, 2); /* create a 2nd argument if there isn't one */
  232. if (lua_next(L, 1))
  233. return 2;
  234. else {
  235. lua_pushnil(L);
  236. return 1;
  237. }
  238. }
  239. static int pairscont (lua_State *L, int status, lua_KContext k) {
  240. (void)L; (void)status; (void)k; /* unused */
  241. return 3;
  242. }
  243. static int luaB_pairs (lua_State *L) {
  244. luaL_checkany(L, 1);
  245. if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */
  246. lua_pushcfunction(L, luaB_next); /* will return generator, */
  247. lua_pushvalue(L, 1); /* state, */
  248. lua_pushnil(L); /* and initial value */
  249. }
  250. else {
  251. lua_pushvalue(L, 1); /* argument 'self' to metamethod */
  252. lua_callk(L, 1, 3, 0, pairscont); /* get 3 values from metamethod */
  253. }
  254. return 3;
  255. }
  256. /*
  257. ** Traversal function for 'ipairs'
  258. */
  259. static int ipairsaux (lua_State *L) {
  260. lua_Integer i = luaL_checkinteger(L, 2);
  261. i = luaL_intop(+, i, 1);
  262. lua_pushinteger(L, i);
  263. return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
  264. }
  265. /*
  266. ** 'ipairs' function. Returns 'ipairsaux', given "table", 0.
  267. ** (The given "table" may not be a table.)
  268. */
  269. static int luaB_ipairs (lua_State *L) {
  270. luaL_checkany(L, 1);
  271. lua_pushcfunction(L, ipairsaux); /* iteration function */
  272. lua_pushvalue(L, 1); /* state */
  273. lua_pushinteger(L, 0); /* initial value */
  274. return 3;
  275. }
  276. static int load_aux (lua_State *L, int status, int envidx) {
  277. if (l_likely(status == LUA_OK)) {
  278. if (envidx != 0) { /* 'env' parameter? */
  279. lua_pushvalue(L, envidx); /* environment for loaded function */
  280. if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */
  281. lua_pop(L, 1); /* remove 'env' if not used by previous call */
  282. }
  283. return 1;
  284. }
  285. else { /* error (message is on top of the stack) */
  286. luaL_pushfail(L);
  287. lua_insert(L, -2); /* put before error message */
  288. return 2; /* return fail plus error message */
  289. }
  290. }
  291. static const char *getmode (lua_State *L, int idx) {
  292. const char *mode = luaL_optstring(L, idx, "bt");
  293. if (strchr(mode, 'B') != NULL) /* Lua code cannot use fixed buffers */
  294. luaL_argerror(L, idx, "invalid mode");
  295. return mode;
  296. }
  297. static int luaB_loadfile (lua_State *L) {
  298. const char *fname = luaL_optstring(L, 1, NULL);
  299. const char *mode = getmode(L, 2);
  300. int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */
  301. int status = luaL_loadfilex(L, fname, mode);
  302. return load_aux(L, status, env);
  303. }
  304. /*
  305. ** {======================================================
  306. ** Generic Read function
  307. ** =======================================================
  308. */
  309. /*
  310. ** reserved slot, above all arguments, to hold a copy of the returned
  311. ** string to avoid it being collected while parsed. 'load' has four
  312. ** optional arguments (chunk, source name, mode, and environment).
  313. */
  314. #define RESERVEDSLOT 5
  315. /*
  316. ** Reader for generic 'load' function: 'lua_load' uses the
  317. ** stack for internal stuff, so the reader cannot change the
  318. ** stack top. Instead, it keeps its resulting string in a
  319. ** reserved slot inside the stack.
  320. */
  321. static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
  322. (void)(ud); /* not used */
  323. luaL_checkstack(L, 2, "too many nested functions");
  324. lua_pushvalue(L, 1); /* get function */
  325. lua_call(L, 0, 1); /* call it */
  326. if (lua_isnil(L, -1)) {
  327. lua_pop(L, 1); /* pop result */
  328. *size = 0;
  329. return NULL;
  330. }
  331. else if (l_unlikely(!lua_isstring(L, -1)))
  332. luaL_error(L, "reader function must return a string");
  333. lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
  334. return lua_tolstring(L, RESERVEDSLOT, size);
  335. }
  336. static int luaB_load (lua_State *L) {
  337. int status;
  338. size_t l;
  339. const char *s = lua_tolstring(L, 1, &l);
  340. const char *mode = getmode(L, 3);
  341. int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */
  342. if (s != NULL) { /* loading a string? */
  343. const char *chunkname = luaL_optstring(L, 2, s);
  344. status = luaL_loadbufferx(L, s, l, chunkname, mode);
  345. }
  346. else { /* loading from a reader function */
  347. const char *chunkname = luaL_optstring(L, 2, "=(load)");
  348. luaL_checktype(L, 1, LUA_TFUNCTION);
  349. lua_settop(L, RESERVEDSLOT); /* create reserved slot */
  350. status = lua_load(L, generic_reader, NULL, chunkname, mode);
  351. }
  352. return load_aux(L, status, env);
  353. }
  354. /* }====================================================== */
  355. static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
  356. (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */
  357. return lua_gettop(L) - 1;
  358. }
  359. static int luaB_dofile (lua_State *L) {
  360. const char *fname = luaL_optstring(L, 1, NULL);
  361. lua_settop(L, 1);
  362. if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK))
  363. return lua_error(L);
  364. lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
  365. return dofilecont(L, 0, 0);
  366. }
  367. static int luaB_assert (lua_State *L) {
  368. if (l_likely(lua_toboolean(L, 1))) /* condition is true? */
  369. return lua_gettop(L); /* return all arguments */
  370. else { /* error */
  371. luaL_checkany(L, 1); /* there must be a condition */
  372. lua_remove(L, 1); /* remove it */
  373. lua_pushliteral(L, "assertion failed!"); /* default message */
  374. lua_settop(L, 1); /* leave only message (default if no other one) */
  375. return luaB_error(L); /* call 'error' */
  376. }
  377. }
  378. static int luaB_select (lua_State *L) {
  379. int n = lua_gettop(L);
  380. if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
  381. lua_pushinteger(L, n-1);
  382. return 1;
  383. }
  384. else {
  385. lua_Integer i = luaL_checkinteger(L, 1);
  386. if (i < 0) i = n + i;
  387. else if (i > n) i = n;
  388. luaL_argcheck(L, 1 <= i, 1, "index out of range");
  389. return n - (int)i;
  390. }
  391. }
  392. /*
  393. ** Continuation function for 'pcall' and 'xpcall'. Both functions
  394. ** already pushed a 'true' before doing the call, so in case of success
  395. ** 'finishpcall' only has to return everything in the stack minus
  396. ** 'extra' values (where 'extra' is exactly the number of items to be
  397. ** ignored).
  398. */
  399. static int finishpcall (lua_State *L, int status, lua_KContext extra) {
  400. if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) { /* error? */
  401. lua_pushboolean(L, 0); /* first result (false) */
  402. lua_pushvalue(L, -2); /* error message */
  403. return 2; /* return false, msg */
  404. }
  405. else
  406. return lua_gettop(L) - (int)extra; /* return all results */
  407. }
  408. static int luaB_pcall (lua_State *L) {
  409. int status;
  410. luaL_checkany(L, 1);
  411. lua_pushboolean(L, 1); /* first result if no errors */
  412. lua_insert(L, 1); /* put it in place */
  413. status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
  414. return finishpcall(L, status, 0);
  415. }
  416. /*
  417. ** Do a protected call with error handling. After 'lua_rotate', the
  418. ** stack will have <f, err, true, f, [args...]>; so, the function passes
  419. ** 2 to 'finishpcall' to skip the 2 first values when returning results.
  420. */
  421. static int luaB_xpcall (lua_State *L) {
  422. int status;
  423. int n = lua_gettop(L);
  424. luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */
  425. lua_pushboolean(L, 1); /* first result */
  426. lua_pushvalue(L, 1); /* function */
  427. lua_rotate(L, 3, 2); /* move them below function's arguments */
  428. status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
  429. return finishpcall(L, status, 2);
  430. }
  431. static int luaB_tostring (lua_State *L) {
  432. luaL_checkany(L, 1);
  433. luaL_tolstring(L, 1, NULL);
  434. return 1;
  435. }
  436. static const luaL_Reg base_funcs[] = {
  437. {"assert", luaB_assert},
  438. {"collectgarbage", luaB_collectgarbage},
  439. {"dofile", luaB_dofile},
  440. {"error", luaB_error},
  441. {"getmetatable", luaB_getmetatable},
  442. {"ipairs", luaB_ipairs},
  443. {"loadfile", luaB_loadfile},
  444. {"load", luaB_load},
  445. {"next", luaB_next},
  446. {"pairs", luaB_pairs},
  447. {"pcall", luaB_pcall},
  448. {"print", luaB_print},
  449. {"warn", luaB_warn},
  450. {"rawequal", luaB_rawequal},
  451. {"rawlen", luaB_rawlen},
  452. {"rawget", luaB_rawget},
  453. {"rawset", luaB_rawset},
  454. {"select", luaB_select},
  455. {"setmetatable", luaB_setmetatable},
  456. {"tonumber", luaB_tonumber},
  457. {"tostring", luaB_tostring},
  458. {"type", luaB_type},
  459. {"xpcall", luaB_xpcall},
  460. /* placeholders */
  461. {LUA_GNAME, NULL},
  462. {"_VERSION", NULL},
  463. {NULL, NULL}
  464. };
  465. LUAMOD_API int luaopen_base (lua_State *L) {
  466. /* open lib into global table */
  467. lua_pushglobaltable(L);
  468. luaL_setfuncs(L, base_funcs, 0);
  469. /* set global _G */
  470. lua_pushvalue(L, -1);
  471. lua_setfield(L, -2, LUA_GNAME);
  472. /* set global _VERSION */
  473. lua_pushliteral(L, LUA_VERSION);
  474. lua_setfield(L, -2, "_VERSION");
  475. return 1;
  476. }