lauxlib.c 17 KB

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