2
0

lbaselib.c 15 KB

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