lauxlib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. /*
  2. ** $Id: lauxlib.c,v 1.105 2003/10/07 20:13:41 roberto Exp roberto $
  3. ** Auxiliary functions for building Lua libraries
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <errno.h>
  8. #include <stdarg.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. /* This file uses only the official API of Lua.
  13. ** Any function declared here could be written as an application function.
  14. */
  15. #define lauxlib_c
  16. #include "lua.h"
  17. #include "lauxlib.h"
  18. /* number of prereserved references (for internal use) */
  19. #define RESERVED_REFS 2
  20. /* reserved references */
  21. #define FREELIST_REF 1 /* free list of references */
  22. #define ARRAYSIZE_REF 2 /* array sizes */
  23. /* convert a stack index to positive */
  24. #define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
  25. lua_gettop(L) + (i) + 1)
  26. /*
  27. ** {======================================================
  28. ** Error-report functions
  29. ** =======================================================
  30. */
  31. LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
  32. lua_Debug ar;
  33. lua_getstack(L, 0, &ar);
  34. lua_getinfo(L, "n", &ar);
  35. if (strcmp(ar.namewhat, "method") == 0) {
  36. narg--; /* do not count `self' */
  37. if (narg == 0) /* error is in the self argument itself? */
  38. return luaL_error(L, "calling `%s' on bad self (%s)", ar.name, extramsg);
  39. }
  40. if (ar.name == NULL)
  41. ar.name = "?";
  42. return luaL_error(L, "bad argument #%d to `%s' (%s)",
  43. narg, ar.name, extramsg);
  44. }
  45. LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
  46. const char *msg = lua_pushfstring(L, "%s expected, got %s",
  47. tname, lua_typename(L, lua_type(L,narg)));
  48. return luaL_argerror(L, narg, msg);
  49. }
  50. static void tag_error (lua_State *L, int narg, int tag) {
  51. luaL_typerror(L, narg, lua_typename(L, tag));
  52. }
  53. LUALIB_API void luaL_where (lua_State *L, int level) {
  54. lua_Debug ar;
  55. if (lua_getstack(L, level, &ar)) { /* check function at level */
  56. lua_getinfo(L, "Sl", &ar); /* get info about it */
  57. if (ar.currentline > 0) { /* is there info? */
  58. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  59. return;
  60. }
  61. }
  62. lua_pushliteral(L, ""); /* else, no information available... */
  63. }
  64. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  65. va_list argp;
  66. va_start(argp, fmt);
  67. luaL_where(L, 1);
  68. lua_pushvfstring(L, fmt, argp);
  69. va_end(argp);
  70. lua_concat(L, 2);
  71. return lua_error(L);
  72. }
  73. /* }====================================================== */
  74. LUALIB_API int luaL_findstring (const char *name, const char *const list[]) {
  75. int i;
  76. for (i=0; list[i]; i++)
  77. if (strcmp(list[i], name) == 0)
  78. return i;
  79. return -1; /* name not found */
  80. }
  81. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  82. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
  83. if (!lua_isnil(L, -1)) /* name already in use? */
  84. return 0; /* leave previous value on top, but return 0 */
  85. lua_pop(L, 1);
  86. lua_newtable(L); /* create metatable */
  87. lua_pushvalue(L, -1);
  88. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  89. lua_pushvalue(L, -1);
  90. lua_pushstring(L, tname);
  91. lua_rawset(L, LUA_REGISTRYINDEX); /* registry[metatable] = name */
  92. return 1;
  93. }
  94. LUALIB_API void luaL_getmetatable (lua_State *L, const char *tname) {
  95. lua_getfield(L, LUA_REGISTRYINDEX, tname);
  96. }
  97. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  98. const char *tn;
  99. if (!lua_getmetatable(L, ud)) return NULL; /* no metatable? */
  100. lua_rawget(L, LUA_REGISTRYINDEX); /* get registry[metatable] */
  101. tn = lua_tostring(L, -1);
  102. if (tn && (strcmp(tn, tname) == 0)) {
  103. lua_pop(L, 1);
  104. return lua_touserdata(L, ud);
  105. }
  106. else {
  107. lua_pop(L, 1);
  108. return NULL;
  109. }
  110. }
  111. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
  112. if (!lua_checkstack(L, space))
  113. luaL_error(L, "stack overflow (%s)", mes);
  114. }
  115. LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
  116. if (lua_type(L, narg) != t)
  117. tag_error(L, narg, t);
  118. }
  119. LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  120. if (lua_type(L, narg) == LUA_TNONE)
  121. luaL_argerror(L, narg, "value expected");
  122. }
  123. LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
  124. const char *s = lua_tostring(L, narg);
  125. if (!s) tag_error(L, narg, LUA_TSTRING);
  126. if (len) *len = lua_strlen(L, narg);
  127. return s;
  128. }
  129. LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
  130. const char *def, size_t *len) {
  131. if (lua_isnoneornil(L, narg)) {
  132. if (len)
  133. *len = (def ? strlen(def) : 0);
  134. return def;
  135. }
  136. else return luaL_checklstring(L, narg, len);
  137. }
  138. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
  139. lua_Number d = lua_tonumber(L, narg);
  140. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  141. tag_error(L, narg, LUA_TNUMBER);
  142. return d;
  143. }
  144. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  145. if (lua_isnoneornil(L, narg)) return def;
  146. else return luaL_checknumber(L, narg);
  147. }
  148. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  149. lua_Integer d = lua_tointeger(L, narg);
  150. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  151. tag_error(L, narg, LUA_TNUMBER);
  152. return d;
  153. }
  154. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  155. lua_Integer def) {
  156. if (lua_isnoneornil(L, narg)) return def;
  157. else return luaL_checkinteger(L, narg);
  158. }
  159. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  160. if (!lua_getmetatable(L, obj)) /* no metatable? */
  161. return 0;
  162. lua_getfield(L, -1, event);
  163. if (lua_isnil(L, -1)) {
  164. lua_pop(L, 2); /* remove metatable and metafield */
  165. return 0;
  166. }
  167. else {
  168. lua_remove(L, -2); /* remove only metatable */
  169. return 1;
  170. }
  171. }
  172. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  173. obj = abs_index(L, obj);
  174. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  175. return 0;
  176. lua_pushvalue(L, obj);
  177. lua_call(L, 1, 1);
  178. return 1;
  179. }
  180. LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
  181. const luaL_reg *l, int nup) {
  182. if (libname) {
  183. /* check whether lib already exists */
  184. lua_getfield(L, LUA_GLOBALSINDEX, libname);
  185. if (lua_isnil(L, -1)) { /* no? */
  186. lua_pop(L, 1);
  187. lua_newtable(L); /* create it */
  188. lua_pushvalue(L, -1);
  189. /* register it with given name */
  190. lua_setfield(L, LUA_GLOBALSINDEX, libname);
  191. }
  192. lua_insert(L, -(nup+1)); /* move library table to below upvalues */
  193. }
  194. for (; l->name; l++) {
  195. int i;
  196. for (i=0; i<nup; i++) /* copy upvalues to the top */
  197. lua_pushvalue(L, -nup);
  198. lua_pushcclosure(L, l->func, nup);
  199. lua_setfield(L, -(nup+2), l->name);
  200. }
  201. lua_pop(L, nup); /* remove upvalues */
  202. }
  203. /*
  204. ** {======================================================
  205. ** getn-setn: size for arrays
  206. ** =======================================================
  207. */
  208. static int checkint (lua_State *L, int topop) {
  209. int n = (int)lua_tointeger(L, -1);
  210. if (n == 0 && !lua_isnumber(L, -1)) n = -1;
  211. lua_pop(L, topop);
  212. return n;
  213. }
  214. static void getsizes (lua_State *L) {
  215. lua_rawgeti(L, LUA_REGISTRYINDEX, ARRAYSIZE_REF);
  216. if (lua_isnil(L, -1)) { /* no `size' table? */
  217. lua_pop(L, 1); /* remove nil */
  218. lua_newtable(L); /* create it */
  219. lua_pushvalue(L, -1); /* `size' will be its own metatable */
  220. lua_setmetatable(L, -2);
  221. lua_pushliteral(L, "kv");
  222. lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */
  223. lua_pushvalue(L, -1);
  224. lua_rawseti(L, LUA_REGISTRYINDEX, ARRAYSIZE_REF); /* store in register */
  225. }
  226. }
  227. void luaL_setn (lua_State *L, int t, int n) {
  228. t = abs_index(L, t);
  229. lua_getfield(L, t, "n");
  230. if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */
  231. lua_pushinteger(L, n);
  232. lua_setfield(L, t, "n");
  233. }
  234. else { /* use `sizes' */
  235. getsizes(L);
  236. lua_pushvalue(L, t);
  237. lua_pushinteger(L, n);
  238. lua_rawset(L, -3); /* sizes[t] = n */
  239. lua_pop(L, 1); /* remove `sizes' */
  240. }
  241. }
  242. int luaL_getn (lua_State *L, int t) {
  243. int n;
  244. t = abs_index(L, t);
  245. lua_getfield(L, t, "n"); /* try t.n */
  246. if ((n = checkint(L, 1)) >= 0) return n;
  247. getsizes(L); /* else try sizes[t] */
  248. lua_pushvalue(L, t);
  249. lua_rawget(L, -2);
  250. if ((n = checkint(L, 2)) >= 0) return n;
  251. for (n = 1; ; n++) { /* else must count elements */
  252. lua_rawgeti(L, t, n);
  253. if (lua_isnil(L, -1)) break;
  254. lua_pop(L, 1);
  255. }
  256. lua_pop(L, 1);
  257. return n - 1;
  258. }
  259. /* }====================================================== */
  260. /*
  261. ** {======================================================
  262. ** Generic Buffer manipulation
  263. ** =======================================================
  264. */
  265. #define bufflen(B) ((B)->p - (B)->buffer)
  266. #define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
  267. #define LIMIT (LUA_MINSTACK/2)
  268. static int emptybuffer (luaL_Buffer *B) {
  269. size_t l = bufflen(B);
  270. if (l == 0) return 0; /* put nothing on stack */
  271. else {
  272. lua_pushlstring(B->L, B->buffer, l);
  273. B->p = B->buffer;
  274. B->lvl++;
  275. return 1;
  276. }
  277. }
  278. static void adjuststack (luaL_Buffer *B) {
  279. if (B->lvl > 1) {
  280. lua_State *L = B->L;
  281. int toget = 1; /* number of levels to concat */
  282. size_t toplen = lua_strlen(L, -1);
  283. do {
  284. size_t l = lua_strlen(L, -(toget+1));
  285. if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
  286. toplen += l;
  287. toget++;
  288. }
  289. else break;
  290. } while (toget < B->lvl);
  291. lua_concat(L, toget);
  292. B->lvl = B->lvl - toget + 1;
  293. }
  294. }
  295. LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
  296. if (emptybuffer(B))
  297. adjuststack(B);
  298. return B->buffer;
  299. }
  300. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  301. while (l--)
  302. luaL_putchar(B, *s++);
  303. }
  304. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  305. luaL_addlstring(B, s, strlen(s));
  306. }
  307. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  308. emptybuffer(B);
  309. lua_concat(B->L, B->lvl);
  310. B->lvl = 1;
  311. }
  312. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  313. lua_State *L = B->L;
  314. size_t vl = lua_strlen(L, -1);
  315. if (vl <= bufffree(B)) { /* fit into buffer? */
  316. memcpy(B->p, lua_tostring(L, -1), vl); /* put it there */
  317. B->p += vl;
  318. lua_pop(L, 1); /* remove from stack */
  319. }
  320. else {
  321. if (emptybuffer(B))
  322. lua_insert(L, -2); /* put buffer before new value */
  323. B->lvl++; /* add new value into B stack */
  324. adjuststack(B);
  325. }
  326. }
  327. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  328. B->L = L;
  329. B->p = B->buffer;
  330. B->lvl = 0;
  331. }
  332. /* }====================================================== */
  333. LUALIB_API int luaL_ref (lua_State *L, int t) {
  334. int ref;
  335. t = abs_index(L, t);
  336. if (lua_isnil(L, -1)) {
  337. lua_pop(L, 1); /* remove from stack */
  338. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  339. }
  340. lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
  341. ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
  342. lua_pop(L, 1); /* remove it from stack */
  343. if (ref != 0) { /* any free element? */
  344. lua_rawgeti(L, t, ref); /* remove it from list */
  345. lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
  346. }
  347. else { /* no free elements */
  348. ref = luaL_getn(L, t);
  349. if (ref < RESERVED_REFS)
  350. ref = RESERVED_REFS; /* skip reserved references */
  351. ref++; /* create new reference */
  352. luaL_setn(L, t, ref);
  353. }
  354. lua_rawseti(L, t, ref);
  355. return ref;
  356. }
  357. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  358. if (ref >= 0) {
  359. t = abs_index(L, t);
  360. lua_rawgeti(L, t, FREELIST_REF);
  361. lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
  362. lua_pushinteger(L, ref);
  363. lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
  364. }
  365. }
  366. /*
  367. ** {======================================================
  368. ** Load functions
  369. ** =======================================================
  370. */
  371. typedef struct LoadF {
  372. int extraline;
  373. FILE *f;
  374. char buff[LUAL_BUFFERSIZE];
  375. } LoadF;
  376. static const char *getF (lua_State *L, void *ud, size_t *size) {
  377. LoadF *lf = (LoadF *)ud;
  378. (void)L;
  379. if (lf->extraline) {
  380. lf->extraline = 0;
  381. *size = 1;
  382. return "\n";
  383. }
  384. if (feof(lf->f)) return NULL;
  385. *size = fread(lf->buff, 1, LUAL_BUFFERSIZE, lf->f);
  386. return (*size > 0) ? lf->buff : NULL;
  387. }
  388. static int errfile (lua_State *L, int fnameindex) {
  389. const char *filename = lua_tostring(L, fnameindex) + 1;
  390. lua_pushfstring(L, "cannot read %s: %s", filename, strerror(errno));
  391. lua_remove(L, fnameindex);
  392. return LUA_ERRFILE;
  393. }
  394. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  395. LoadF lf;
  396. int status, readstatus;
  397. int c;
  398. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  399. lf.extraline = 0;
  400. if (filename == NULL) {
  401. lua_pushliteral(L, "=stdin");
  402. lf.f = stdin;
  403. }
  404. else {
  405. lua_pushfstring(L, "@%s", filename);
  406. lf.f = fopen(filename, "r");
  407. }
  408. if (lf.f == NULL) return errfile(L, fnameindex); /* unable to open file */
  409. c = getc(lf.f);
  410. if (c == '#') { /* Unix exec. file? */
  411. lf.extraline = 1;
  412. while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
  413. if (c == '\n') c = getc(lf.f);
  414. }
  415. if (c == LUA_SIGNATURE[0] && lf.f != stdin) { /* binary file? */
  416. fclose(lf.f);
  417. lf.f = fopen(filename, "rb"); /* reopen in binary mode */
  418. if (lf.f == NULL) return errfile(L, fnameindex); /* unable to reopen file */
  419. /* skip eventual `#!...' */
  420. while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
  421. lf.extraline = 0;
  422. }
  423. ungetc(c, lf.f);
  424. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  425. readstatus = ferror(lf.f);
  426. if (lf.f != stdin) fclose(lf.f); /* close file (even in case of errors) */
  427. if (readstatus) {
  428. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  429. return errfile(L, fnameindex);
  430. }
  431. lua_remove(L, fnameindex);
  432. return status;
  433. }
  434. typedef struct LoadS {
  435. const char *s;
  436. size_t size;
  437. } LoadS;
  438. static const char *getS (lua_State *L, void *ud, size_t *size) {
  439. LoadS *ls = (LoadS *)ud;
  440. (void)L;
  441. if (ls->size == 0) return NULL;
  442. *size = ls->size;
  443. ls->size = 0;
  444. return ls->s;
  445. }
  446. LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
  447. const char *name) {
  448. LoadS ls;
  449. ls.s = buff;
  450. ls.size = size;
  451. return lua_load(L, getS, &ls, name);
  452. }
  453. /* }====================================================== */
  454. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  455. (void)ud;
  456. if (nsize == 0) {
  457. free(ptr);
  458. return NULL;
  459. }
  460. else
  461. return realloc(ptr, nsize);
  462. }
  463. LUALIB_API lua_State *luaL_newstate (void) {
  464. return lua_newstate(l_alloc, NULL);
  465. }
  466. /*
  467. ** {======================================================
  468. ** compatibility code
  469. ** =======================================================
  470. */
  471. static void callalert (lua_State *L, int status) {
  472. if (status != 0) {
  473. lua_getglobal(L, "_ALERT");
  474. if (lua_isfunction(L, -1)) {
  475. lua_insert(L, -2);
  476. lua_call(L, 1, 0);
  477. }
  478. else { /* no _ALERT function; print it on stderr */
  479. fprintf(stderr, "%s\n", lua_tostring(L, -2));
  480. lua_pop(L, 2); /* remove error message and _ALERT */
  481. }
  482. }
  483. }
  484. static int aux_do (lua_State *L, int status) {
  485. if (status == 0) { /* parse OK? */
  486. status = lua_pcall(L, 0, LUA_MULTRET, 0); /* call main */
  487. }
  488. callalert(L, status);
  489. return status;
  490. }
  491. LUALIB_API int lua_dofile (lua_State *L, const char *filename) {
  492. return aux_do(L, luaL_loadfile(L, filename));
  493. }
  494. LUALIB_API int lua_dobuffer (lua_State *L, const char *buff, size_t size,
  495. const char *name) {
  496. return aux_do(L, luaL_loadbuffer(L, buff, size, name));
  497. }
  498. LUALIB_API int lua_dostring (lua_State *L, const char *str) {
  499. return lua_dobuffer(L, str, strlen(str), str);
  500. }
  501. /* }====================================================== */