lbaselib.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /*
  2. ** $Id: lbaselib.c,v 1.253 2010/12/07 11:40:42 roberto Exp roberto $
  3. ** Basic library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #define lbaselib_c
  11. #define LUA_LIB
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. static int luaB_print (lua_State *L) {
  16. int n = lua_gettop(L); /* number of arguments */
  17. int i;
  18. lua_getglobal(L, "tostring");
  19. for (i=1; i<=n; i++) {
  20. const char *s;
  21. size_t l;
  22. lua_pushvalue(L, -1); /* function to be called */
  23. lua_pushvalue(L, i); /* value to print */
  24. lua_call(L, 1, 1);
  25. s = lua_tolstring(L, -1, &l); /* get result */
  26. if (s == NULL)
  27. return luaL_error(L, LUA_QL("tostring") " must return a string to "
  28. LUA_QL("print"));
  29. if (i>1) luai_writestring("\t", 1);
  30. luai_writestring(s, l);
  31. lua_pop(L, 1); /* pop result */
  32. }
  33. luai_writestring("\n", 1);
  34. return 0;
  35. }
  36. #define SPACECHARS " \f\n\r\t\v"
  37. static int luaB_tonumber (lua_State *L) {
  38. int base = luaL_optint(L, 2, 10);
  39. if (base == 10) { /* standard conversion */
  40. luaL_checkany(L, 1);
  41. if (lua_isnumber(L, 1)) {
  42. lua_pushnumber(L, lua_tonumber(L, 1));
  43. return 1;
  44. }
  45. }
  46. else {
  47. size_t l1;
  48. const char *s1 = luaL_checklstring(L, 1, &l1);
  49. const char *e1 = s1 + l1;
  50. char *s2;
  51. unsigned long n;
  52. int neg = 0;
  53. luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
  54. s1 += strspn(s1, SPACECHARS); /* skip initial spaces */
  55. if (*s1 == '-') { s1++; neg = 1; }
  56. n = strtoul(s1, &s2, base);
  57. if (s1 != s2) { /* at least one valid digit? */
  58. s2 += strspn(s2, SPACECHARS); /* skip trailing spaces */
  59. if (s2 == e1) { /* no invalid trailing characters? */
  60. lua_pushnumber(L, (neg) ? -(lua_Number)n : (lua_Number)n);
  61. return 1;
  62. }
  63. }
  64. }
  65. lua_pushnil(L); /* else not a number */
  66. return 1;
  67. }
  68. static int luaB_error (lua_State *L) {
  69. int level = luaL_optint(L, 2, 1);
  70. lua_settop(L, 1);
  71. if (lua_isstring(L, 1) && level > 0) { /* add extra information? */
  72. luaL_where(L, level);
  73. lua_pushvalue(L, 1);
  74. lua_concat(L, 2);
  75. }
  76. return lua_error(L);
  77. }
  78. static int luaB_getmetatable (lua_State *L) {
  79. luaL_checkany(L, 1);
  80. if (!lua_getmetatable(L, 1)) {
  81. lua_pushnil(L);
  82. return 1; /* no metatable */
  83. }
  84. luaL_getmetafield(L, 1, "__metatable");
  85. return 1; /* returns either __metatable field (if present) or metatable */
  86. }
  87. static int luaB_setmetatable (lua_State *L) {
  88. int t = lua_type(L, 2);
  89. luaL_checktype(L, 1, LUA_TTABLE);
  90. luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
  91. "nil or table expected");
  92. if (luaL_getmetafield(L, 1, "__metatable"))
  93. return luaL_error(L, "cannot change a protected metatable");
  94. lua_settop(L, 2);
  95. lua_setmetatable(L, 1);
  96. return 1;
  97. }
  98. static int luaB_deprecated (lua_State *L) {
  99. return luaL_error(L, "deprecated function");
  100. }
  101. static int luaB_rawequal (lua_State *L) {
  102. luaL_checkany(L, 1);
  103. luaL_checkany(L, 2);
  104. lua_pushboolean(L, lua_rawequal(L, 1, 2));
  105. return 1;
  106. }
  107. static int luaB_rawget (lua_State *L) {
  108. luaL_checktype(L, 1, LUA_TTABLE);
  109. luaL_checkany(L, 2);
  110. lua_settop(L, 2);
  111. lua_rawget(L, 1);
  112. return 1;
  113. }
  114. static int luaB_rawset (lua_State *L) {
  115. luaL_checktype(L, 1, LUA_TTABLE);
  116. luaL_checkany(L, 2);
  117. luaL_checkany(L, 3);
  118. lua_settop(L, 3);
  119. lua_rawset(L, 1);
  120. return 1;
  121. }
  122. static int luaB_collectgarbage (lua_State *L) {
  123. static const char *const opts[] = {"stop", "restart", "collect",
  124. "count", "step", "setpause", "setstepmul",
  125. "setmajorinc", "isrunning", "gen", "inc", NULL};
  126. static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
  127. LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
  128. LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
  129. int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
  130. int ex = luaL_optint(L, 2, 0);
  131. int res = lua_gc(L, o, ex);
  132. switch (o) {
  133. case LUA_GCCOUNT: {
  134. int b = lua_gc(L, LUA_GCCOUNTB, 0);
  135. lua_pushnumber(L, res + ((lua_Number)b/1024));
  136. lua_pushinteger(L, b);
  137. return 2;
  138. }
  139. case LUA_GCSTEP: case LUA_GCISRUNNING: {
  140. lua_pushboolean(L, res);
  141. return 1;
  142. }
  143. default: {
  144. lua_pushinteger(L, res);
  145. return 1;
  146. }
  147. }
  148. }
  149. static int luaB_type (lua_State *L) {
  150. luaL_checkany(L, 1);
  151. lua_pushstring(L, luaL_typename(L, 1));
  152. return 1;
  153. }
  154. static int pairsmeta (lua_State *L, const char *method, int iszero,
  155. lua_CFunction iter) {
  156. if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */
  157. luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */
  158. lua_pushcfunction(L, iter); /* will return generator, */
  159. lua_pushvalue(L, 1); /* state, */
  160. if (iszero) lua_pushinteger(L, 0); /* and initial value */
  161. else lua_pushnil(L);
  162. }
  163. else {
  164. lua_pushvalue(L, 1); /* argument 'self' to metamethod */
  165. lua_call(L, 1, 3); /* get 3 values from metamethod */
  166. }
  167. return 3;
  168. }
  169. static int luaB_next (lua_State *L) {
  170. luaL_checktype(L, 1, LUA_TTABLE);
  171. lua_settop(L, 2); /* create a 2nd argument if there isn't one */
  172. if (lua_next(L, 1))
  173. return 2;
  174. else {
  175. lua_pushnil(L);
  176. return 1;
  177. }
  178. }
  179. static int luaB_pairs (lua_State *L) {
  180. return pairsmeta(L, "__pairs", 0, luaB_next);
  181. }
  182. static int ipairsaux (lua_State *L) {
  183. int i = luaL_checkint(L, 2);
  184. luaL_checktype(L, 1, LUA_TTABLE);
  185. i++; /* next value */
  186. lua_pushinteger(L, i);
  187. lua_rawgeti(L, 1, i);
  188. return (lua_isnil(L, -1)) ? 1 : 2;
  189. }
  190. static int luaB_ipairs (lua_State *L) {
  191. return pairsmeta(L, "__ipairs", 1, ipairsaux);
  192. }
  193. static int load_aux (lua_State *L, int status) {
  194. if (status == LUA_OK)
  195. return 1;
  196. else {
  197. lua_pushnil(L);
  198. lua_insert(L, -2); /* put before error message */
  199. return 2; /* return nil plus error message */
  200. }
  201. }
  202. static int luaB_loadfile (lua_State *L) {
  203. const char *fname = luaL_optstring(L, 1, NULL);
  204. return load_aux(L, luaL_loadfile(L, fname));
  205. }
  206. /*
  207. ** {======================================================
  208. ** Generic Read function
  209. ** =======================================================
  210. */
  211. static const char *checkrights (lua_State *L, const char *mode, const char *s) {
  212. if (strchr(mode, 'b') == NULL && *s == LUA_SIGNATURE[0])
  213. return lua_pushstring(L, "attempt to load a binary chunk");
  214. if (strchr(mode, 't') == NULL && *s != LUA_SIGNATURE[0])
  215. return lua_pushstring(L, "attempt to load a text chunk");
  216. return NULL; /* chunk in allowed format */
  217. }
  218. /*
  219. ** reserves a slot, above all arguments, to hold a copy of the returned
  220. ** string to avoid it being collected while parsed
  221. */
  222. #define RESERVEDSLOT 4
  223. /*
  224. ** Reader for generic `load' function: `lua_load' uses the
  225. ** stack for internal stuff, so the reader cannot change the
  226. ** stack top. Instead, it keeps its resulting string in a
  227. ** reserved slot inside the stack.
  228. */
  229. typedef struct { /* reader state */
  230. int f; /* position of reader function on stack */
  231. const char *mode; /* allowed modes (binary/text) */
  232. } Readstat;
  233. static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
  234. const char *s;
  235. Readstat *stat = (Readstat *)ud;
  236. luaL_checkstack(L, 2, "too many nested functions");
  237. lua_pushvalue(L, stat->f); /* get function */
  238. lua_call(L, 0, 1); /* call it */
  239. if (lua_isnil(L, -1)) {
  240. *size = 0;
  241. return NULL;
  242. }
  243. else if ((s = lua_tostring(L, -1)) != NULL) {
  244. if (stat->mode != NULL) { /* first time? */
  245. s = checkrights(L, stat->mode, s); /* check mode */
  246. stat->mode = NULL; /* to avoid further checks */
  247. if (s) luaL_error(L, s);
  248. }
  249. lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
  250. return lua_tolstring(L, RESERVEDSLOT, size);
  251. }
  252. else {
  253. luaL_error(L, "reader function must return a string");
  254. return NULL; /* to avoid warnings */
  255. }
  256. }
  257. static int luaB_load_aux (lua_State *L, int farg) {
  258. int status;
  259. Readstat stat;
  260. size_t l;
  261. const char *s = lua_tolstring(L, farg, &l);
  262. stat.mode = luaL_optstring(L, farg + 2, "bt");
  263. if (s != NULL) { /* loading a string? */
  264. const char *chunkname = luaL_optstring(L, farg + 1, s);
  265. status = (checkrights(L, stat.mode, s) != NULL)
  266. || luaL_loadbuffer(L, s, l, chunkname);
  267. }
  268. else { /* loading from a reader function */
  269. const char *chunkname = luaL_optstring(L, farg + 1, "=(load)");
  270. luaL_checktype(L, farg, LUA_TFUNCTION);
  271. stat.f = farg;
  272. lua_settop(L, RESERVEDSLOT); /* create reserved slot */
  273. status = lua_load(L, generic_reader, &stat, chunkname);
  274. }
  275. return load_aux(L, status);
  276. }
  277. static int luaB_load (lua_State *L) {
  278. return luaB_load_aux(L, 1);
  279. }
  280. static int luaB_loadin (lua_State *L) {
  281. int n;
  282. luaL_checkany(L, 1);
  283. n = luaB_load_aux(L, 2);
  284. if (n == 1) { /* success? */
  285. lua_pushvalue(L, 1); /* environment for loaded function */
  286. if (lua_setupvalue(L, -2, 1) == NULL)
  287. luaL_error(L, "loaded chunk does not have an upvalue");
  288. }
  289. return n;
  290. }
  291. #if defined(LUA_COMPAT_LOADSTRING)
  292. #define luaB_loadstring luaB_load
  293. #else
  294. #define luaB_loadstring luaB_deprecated
  295. #endif
  296. /* }====================================================== */
  297. static int dofilecont (lua_State *L) {
  298. return lua_gettop(L) - 1;
  299. }
  300. static int luaB_dofile (lua_State *L) {
  301. const char *fname = luaL_optstring(L, 1, NULL);
  302. lua_settop(L, 1);
  303. if (luaL_loadfile(L, fname) != LUA_OK) lua_error(L);
  304. lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
  305. return dofilecont(L);
  306. }
  307. static int luaB_assert (lua_State *L) {
  308. if (!lua_toboolean(L, 1))
  309. return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
  310. return lua_gettop(L);
  311. }
  312. static int luaB_select (lua_State *L) {
  313. int n = lua_gettop(L);
  314. if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
  315. lua_pushinteger(L, n-1);
  316. return 1;
  317. }
  318. else {
  319. int i = luaL_checkint(L, 1);
  320. if (i < 0) i = n + i;
  321. else if (i > n) i = n;
  322. luaL_argcheck(L, 1 <= i, 1, "index out of range");
  323. return n - i;
  324. }
  325. }
  326. static int pcallcont (lua_State *L) {
  327. int errfunc; /* call has an error function in bottom of the stack */
  328. int status = lua_getctx(L, &errfunc);
  329. lua_assert(status != LUA_OK);
  330. lua_pushboolean(L, (status == LUA_YIELD)); /* first result (status) */
  331. if (errfunc) /* came from xpcall? */
  332. lua_replace(L, 1); /* put first result in place of error function */
  333. else /* came from pcall */
  334. lua_insert(L, 1); /* open space for first result */
  335. return lua_gettop(L);
  336. }
  337. static int luaB_pcall (lua_State *L) {
  338. int status;
  339. luaL_checkany(L, 1);
  340. status = lua_pcallk(L, lua_gettop(L) - 1, LUA_MULTRET, 0, 0, pcallcont);
  341. luaL_checkstack(L, 1, NULL);
  342. lua_pushboolean(L, (status == LUA_OK));
  343. lua_insert(L, 1);
  344. return lua_gettop(L); /* return status + all results */
  345. }
  346. static int luaB_xpcall (lua_State *L) {
  347. int status;
  348. int n = lua_gettop(L);
  349. luaL_argcheck(L, n >= 2, 2, "value expected");
  350. lua_pushvalue(L, 1); /* exchange function... */
  351. lua_copy(L, 2, 1); /* ...and error handler */
  352. lua_replace(L, 2);
  353. status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 1, pcallcont);
  354. luaL_checkstack(L, 1, NULL);
  355. lua_pushboolean(L, (status == LUA_OK));
  356. lua_replace(L, 1);
  357. return lua_gettop(L); /* return status + all results */
  358. }
  359. static int luaB_tostring (lua_State *L) {
  360. luaL_checkany(L, 1);
  361. luaL_tolstring(L, 1, NULL);
  362. return 1;
  363. }
  364. static int luaB_newproxy (lua_State *L) {
  365. lua_settop(L, 1);
  366. lua_newuserdata(L, 0); /* create proxy */
  367. if (lua_toboolean(L, 1) == 0)
  368. return 1; /* no metatable */
  369. else if (lua_isboolean(L, 1)) {
  370. lua_createtable(L, 0, 1); /* create a new metatable `m' ... */
  371. lua_pushboolean(L, 1);
  372. lua_setfield(L, -2, "__gc"); /* ... m.__gc = false (HACK!!)... */
  373. lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
  374. lua_pushboolean(L, 1);
  375. lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
  376. }
  377. else {
  378. int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
  379. if (lua_getmetatable(L, 1)) {
  380. lua_rawget(L, lua_upvalueindex(1));
  381. validproxy = lua_toboolean(L, -1);
  382. lua_pop(L, 1); /* remove value */
  383. }
  384. luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
  385. lua_getmetatable(L, 1); /* metatable is valid; get it */
  386. }
  387. lua_setmetatable(L, 2);
  388. return 1;
  389. }
  390. static const luaL_Reg base_funcs[] = {
  391. {"assert", luaB_assert},
  392. {"collectgarbage", luaB_collectgarbage},
  393. {"dofile", luaB_dofile},
  394. {"error", luaB_error},
  395. {"getfenv", luaB_deprecated},
  396. {"getmetatable", luaB_getmetatable},
  397. {"ipairs", luaB_ipairs},
  398. {"loadfile", luaB_loadfile},
  399. {"load", luaB_load},
  400. {"loadin", luaB_loadin},
  401. {"loadstring", luaB_loadstring},
  402. {"next", luaB_next},
  403. {"pairs", luaB_pairs},
  404. {"pcall", luaB_pcall},
  405. {"print", luaB_print},
  406. {"rawequal", luaB_rawequal},
  407. {"rawget", luaB_rawget},
  408. {"rawset", luaB_rawset},
  409. {"select", luaB_select},
  410. {"setfenv", luaB_deprecated},
  411. {"setmetatable", luaB_setmetatable},
  412. {"tonumber", luaB_tonumber},
  413. {"tostring", luaB_tostring},
  414. {"type", luaB_type},
  415. {"xpcall", luaB_xpcall},
  416. {NULL, NULL}
  417. };
  418. LUAMOD_API int luaopen_base (lua_State *L) {
  419. /* set global _G */
  420. lua_pushglobaltable(L);
  421. lua_pushglobaltable(L);
  422. lua_setfield(L, -2, "_G");
  423. /* open lib into global table */
  424. luaL_setfuncs(L, base_funcs, 0);
  425. lua_pushliteral(L, LUA_VERSION);
  426. lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */
  427. /* `newproxy' needs a weaktable as upvalue */
  428. lua_createtable(L, 0, 1); /* new table `w' */
  429. lua_pushvalue(L, -1); /* `w' will be its own metatable */
  430. lua_setmetatable(L, -2);
  431. lua_pushliteral(L, "kv");
  432. lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
  433. lua_pushcclosure(L, luaB_newproxy, 1);
  434. lua_setfield(L, -2, "newproxy"); /* set global `newproxy' */
  435. return 1;
  436. }