lbaselib.c 14 KB

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