2
0

lauxlib.c 16 KB

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