lbaselib.c 14 KB

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