lauxlib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. /*
  2. ** $Id: lauxlib.c,v 1.107 2003/10/20 18:32:55 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_getglobal(L, 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_setglobal(L, 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. getsizes(L);
  230. lua_pushvalue(L, t);
  231. lua_pushinteger(L, n);
  232. lua_rawset(L, -3); /* sizes[t] = n */
  233. lua_pop(L, 1); /* remove `sizes' */
  234. }
  235. int luaL_getn (lua_State *L, int t) {
  236. int n;
  237. t = abs_index(L, t);
  238. getsizes(L); /* try sizes[t] */
  239. lua_pushvalue(L, t);
  240. lua_rawget(L, -2);
  241. if ((n = checkint(L, 2)) >= 0) return n;
  242. lua_getfield(L, t, "n"); /* else try t.n */
  243. if ((n = checkint(L, 1)) >= 0) return n;
  244. for (n = 1; ; n++) { /* else must count elements */
  245. lua_rawgeti(L, t, n);
  246. if (lua_isnil(L, -1)) break;
  247. lua_pop(L, 1);
  248. }
  249. lua_pop(L, 1);
  250. return n - 1;
  251. }
  252. /* }====================================================== */
  253. /*
  254. ** {======================================================
  255. ** Generic Buffer manipulation
  256. ** =======================================================
  257. */
  258. #define bufflen(B) ((B)->p - (B)->buffer)
  259. #define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
  260. #define LIMIT (LUA_MINSTACK/2)
  261. static int emptybuffer (luaL_Buffer *B) {
  262. size_t l = bufflen(B);
  263. if (l == 0) return 0; /* put nothing on stack */
  264. else {
  265. lua_pushlstring(B->L, B->buffer, l);
  266. B->p = B->buffer;
  267. B->lvl++;
  268. return 1;
  269. }
  270. }
  271. static void adjuststack (luaL_Buffer *B) {
  272. if (B->lvl > 1) {
  273. lua_State *L = B->L;
  274. int toget = 1; /* number of levels to concat */
  275. size_t toplen = lua_strlen(L, -1);
  276. do {
  277. size_t l = lua_strlen(L, -(toget+1));
  278. if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
  279. toplen += l;
  280. toget++;
  281. }
  282. else break;
  283. } while (toget < B->lvl);
  284. lua_concat(L, toget);
  285. B->lvl = B->lvl - toget + 1;
  286. }
  287. }
  288. LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
  289. if (emptybuffer(B))
  290. adjuststack(B);
  291. return B->buffer;
  292. }
  293. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  294. while (l--)
  295. luaL_putchar(B, *s++);
  296. }
  297. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  298. luaL_addlstring(B, s, strlen(s));
  299. }
  300. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  301. emptybuffer(B);
  302. lua_concat(B->L, B->lvl);
  303. B->lvl = 1;
  304. }
  305. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  306. lua_State *L = B->L;
  307. size_t vl = lua_strlen(L, -1);
  308. if (vl <= bufffree(B)) { /* fit into buffer? */
  309. memcpy(B->p, lua_tostring(L, -1), vl); /* put it there */
  310. B->p += vl;
  311. lua_pop(L, 1); /* remove from stack */
  312. }
  313. else {
  314. if (emptybuffer(B))
  315. lua_insert(L, -2); /* put buffer before new value */
  316. B->lvl++; /* add new value into B stack */
  317. adjuststack(B);
  318. }
  319. }
  320. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  321. B->L = L;
  322. B->p = B->buffer;
  323. B->lvl = 0;
  324. }
  325. /* }====================================================== */
  326. LUALIB_API int luaL_ref (lua_State *L, int t) {
  327. int ref;
  328. t = abs_index(L, t);
  329. if (lua_isnil(L, -1)) {
  330. lua_pop(L, 1); /* remove from stack */
  331. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  332. }
  333. lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
  334. ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
  335. lua_pop(L, 1); /* remove it from stack */
  336. if (ref != 0) { /* any free element? */
  337. lua_rawgeti(L, t, ref); /* remove it from list */
  338. lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
  339. }
  340. else { /* no free elements */
  341. ref = luaL_getn(L, t);
  342. if (ref < RESERVED_REFS)
  343. ref = RESERVED_REFS; /* skip reserved references */
  344. ref++; /* create new reference */
  345. luaL_setn(L, t, ref);
  346. }
  347. lua_rawseti(L, t, ref);
  348. return ref;
  349. }
  350. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  351. if (ref >= 0) {
  352. t = abs_index(L, t);
  353. lua_rawgeti(L, t, FREELIST_REF);
  354. lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
  355. lua_pushinteger(L, ref);
  356. lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
  357. }
  358. }
  359. /*
  360. ** {======================================================
  361. ** Load functions
  362. ** =======================================================
  363. */
  364. typedef struct LoadF {
  365. int extraline;
  366. FILE *f;
  367. char buff[LUAL_BUFFERSIZE];
  368. } LoadF;
  369. static const char *getF (lua_State *L, void *ud, size_t *size) {
  370. LoadF *lf = (LoadF *)ud;
  371. (void)L;
  372. if (lf->extraline) {
  373. lf->extraline = 0;
  374. *size = 1;
  375. return "\n";
  376. }
  377. if (feof(lf->f)) return NULL;
  378. *size = fread(lf->buff, 1, LUAL_BUFFERSIZE, lf->f);
  379. return (*size > 0) ? lf->buff : NULL;
  380. }
  381. static int errfile (lua_State *L, int fnameindex) {
  382. const char *filename = lua_tostring(L, fnameindex) + 1;
  383. lua_pushfstring(L, "cannot read %s: %s", filename, strerror(errno));
  384. lua_remove(L, fnameindex);
  385. return LUA_ERRFILE;
  386. }
  387. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  388. LoadF lf;
  389. int status, readstatus;
  390. int c;
  391. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  392. lf.extraline = 0;
  393. if (filename == NULL) {
  394. lua_pushliteral(L, "=stdin");
  395. lf.f = stdin;
  396. }
  397. else {
  398. lua_pushfstring(L, "@%s", filename);
  399. lf.f = fopen(filename, "r");
  400. }
  401. if (lf.f == NULL) return errfile(L, fnameindex); /* unable to open file */
  402. c = getc(lf.f);
  403. if (c == '#') { /* Unix exec. file? */
  404. lf.extraline = 1;
  405. while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
  406. if (c == '\n') c = getc(lf.f);
  407. }
  408. if (c == LUA_SIGNATURE[0] && lf.f != stdin) { /* binary file? */
  409. fclose(lf.f);
  410. lf.f = fopen(filename, "rb"); /* reopen in binary mode */
  411. if (lf.f == NULL) return errfile(L, fnameindex); /* unable to reopen file */
  412. /* skip eventual `#!...' */
  413. while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
  414. lf.extraline = 0;
  415. }
  416. ungetc(c, lf.f);
  417. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  418. readstatus = ferror(lf.f);
  419. if (lf.f != stdin) fclose(lf.f); /* close file (even in case of errors) */
  420. if (readstatus) {
  421. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  422. return errfile(L, fnameindex);
  423. }
  424. lua_remove(L, fnameindex);
  425. return status;
  426. }
  427. typedef struct LoadS {
  428. const char *s;
  429. size_t size;
  430. } LoadS;
  431. static const char *getS (lua_State *L, void *ud, size_t *size) {
  432. LoadS *ls = (LoadS *)ud;
  433. (void)L;
  434. if (ls->size == 0) return NULL;
  435. *size = ls->size;
  436. ls->size = 0;
  437. return ls->s;
  438. }
  439. LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
  440. const char *name) {
  441. LoadS ls;
  442. ls.s = buff;
  443. ls.size = size;
  444. return lua_load(L, getS, &ls, name);
  445. }
  446. /* }====================================================== */
  447. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  448. (void)ud;
  449. if (nsize == 0) {
  450. free(ptr);
  451. return NULL;
  452. }
  453. else
  454. return realloc(ptr, nsize);
  455. }
  456. LUALIB_API lua_State *luaL_newstate (void) {
  457. return lua_newstate(l_alloc, NULL);
  458. }
  459. /*
  460. ** {======================================================
  461. ** compatibility code
  462. ** =======================================================
  463. */
  464. static void callalert (lua_State *L, int status) {
  465. if (status != 0) {
  466. lua_getglobal(L, "_ALERT");
  467. if (lua_isfunction(L, -1)) {
  468. lua_insert(L, -2);
  469. lua_call(L, 1, 0);
  470. }
  471. else { /* no _ALERT function; print it on stderr */
  472. fprintf(stderr, "%s\n", lua_tostring(L, -2));
  473. lua_pop(L, 2); /* remove error message and _ALERT */
  474. }
  475. }
  476. }
  477. static int aux_do (lua_State *L, int status) {
  478. if (status == 0) { /* parse OK? */
  479. status = lua_pcall(L, 0, LUA_MULTRET, 0); /* call main */
  480. }
  481. callalert(L, status);
  482. return status;
  483. }
  484. LUALIB_API int lua_dofile (lua_State *L, const char *filename) {
  485. return aux_do(L, luaL_loadfile(L, filename));
  486. }
  487. LUALIB_API int lua_dobuffer (lua_State *L, const char *buff, size_t size,
  488. const char *name) {
  489. return aux_do(L, luaL_loadbuffer(L, buff, size, name));
  490. }
  491. LUALIB_API int lua_dostring (lua_State *L, const char *str) {
  492. return lua_dobuffer(L, str, strlen(str), str);
  493. }
  494. /* }====================================================== */