lbaselib.c 15 KB

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