lauxlib.c 14 KB

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