lauxlib.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. /*
  2. ** $Id: lauxlib.c,v 1.207 2010/04/09 16:14:46 roberto Exp roberto $
  3. ** Auxiliary functions for building Lua libraries
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <errno.h>
  7. #include <stdarg.h>
  8. #include <stdio.h>
  9. #include <stdlib.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. #define LUA_LIB
  16. #include "lua.h"
  17. #include "lauxlib.h"
  18. /* convert a stack index to positive */
  19. #define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
  20. lua_gettop(L) + (i) + 1)
  21. /*
  22. ** {======================================================
  23. ** Traceback
  24. ** =======================================================
  25. */
  26. #define LEVELS1 12 /* size of the first part of the stack */
  27. #define LEVELS2 10 /* size of the second part of the stack */
  28. /*
  29. ** search for 'objidx' in table at index -1.
  30. ** return 1 + string at top if find a good name.
  31. */
  32. static int findfield (lua_State *L, int objidx, int level) {
  33. int found = 0;
  34. if (level == 0 || !lua_istable(L, -1))
  35. return 0; /* not found */
  36. lua_pushnil(L); /* start 'next' loop */
  37. while (!found && lua_next(L, -2)) { /* for each pair in table */
  38. if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
  39. if (lua_rawequal(L, objidx, -1)) { /* found object? */
  40. lua_pop(L, 1); /* remove value (but keep name) */
  41. return 1;
  42. }
  43. else if (findfield(L, objidx, level - 1)) { /* try recursively */
  44. lua_remove(L, -2); /* remove table (but keep name) */
  45. lua_pushliteral(L, ".");
  46. lua_insert(L, -2); /* place '.' between the two names */
  47. lua_concat(L, 3);
  48. return 1;
  49. }
  50. }
  51. lua_pop(L, 1); /* remove value */
  52. }
  53. return 0; /* not found */
  54. }
  55. static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
  56. int top = lua_gettop(L);
  57. lua_getinfo(L, "f", ar); /* push function */
  58. lua_pushglobaltable(L);
  59. if (findfield(L, top + 1, 2)) {
  60. lua_copy(L, -1, top + 1); /* move name to proper place */
  61. lua_pop(L, 2); /* remove pushed values */
  62. return 1;
  63. }
  64. else {
  65. lua_settop(L, top); /* remove function and global table */
  66. return 0;
  67. }
  68. }
  69. static void pushfuncname (lua_State *L, lua_Debug *ar) {
  70. if (*ar->namewhat != '\0') /* is there a name? */
  71. lua_pushfstring(L, "function " LUA_QS, ar->name);
  72. else if (*ar->what == 'm') /* main? */
  73. lua_pushfstring(L, "main chunk");
  74. else if (*ar->what == 'C' || *ar->what == 't') {
  75. if (pushglobalfuncname(L, ar)) {
  76. lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
  77. lua_remove(L, -2); /* remove name */
  78. }
  79. else
  80. lua_pushliteral(L, "?");
  81. }
  82. else
  83. lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
  84. }
  85. static int countlevels (lua_State *L) {
  86. lua_Debug ar;
  87. int li = 1, le = 1;
  88. /* find an upper bound */
  89. while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
  90. /* do a binary search */
  91. while (li < le) {
  92. int m = (li + le)/2;
  93. if (lua_getstack(L, m, &ar)) li = m + 1;
  94. else le = m;
  95. }
  96. return le - 1;
  97. }
  98. LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
  99. const char *msg, int level) {
  100. lua_Debug ar;
  101. int top = lua_gettop(L);
  102. int numlevels = countlevels(L1);
  103. int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;
  104. if (msg) lua_pushfstring(L, "%s\n", msg);
  105. lua_pushliteral(L, "stack traceback:");
  106. while (lua_getstack(L1, level++, &ar)) {
  107. if (level == mark) { /* too many levels? */
  108. lua_pushliteral(L, "\n\t..."); /* add a '...' */
  109. level = numlevels - LEVELS2; /* and skip to last ones */
  110. }
  111. else {
  112. lua_getinfo(L1, "Slnt", &ar);
  113. lua_pushfstring(L, "\n\t%s:", ar.short_src);
  114. if (ar.currentline > 0)
  115. lua_pushfstring(L, "%d:", ar.currentline);
  116. lua_pushliteral(L, " in ");
  117. pushfuncname(L, &ar);
  118. if (ar.istailcall)
  119. lua_pushliteral(L, "\n\t(...tail calls...)");
  120. lua_concat(L, lua_gettop(L) - top);
  121. }
  122. }
  123. lua_concat(L, lua_gettop(L) - top);
  124. }
  125. /* }====================================================== */
  126. /*
  127. ** {======================================================
  128. ** Error-report functions
  129. ** =======================================================
  130. */
  131. LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
  132. lua_Debug ar;
  133. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  134. return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
  135. lua_getinfo(L, "n", &ar);
  136. if (strcmp(ar.namewhat, "method") == 0) {
  137. narg--; /* do not count `self' */
  138. if (narg == 0) /* error is in the self argument itself? */
  139. return luaL_error(L, "calling " LUA_QS " on bad self", ar.name);
  140. }
  141. if (ar.name == NULL)
  142. ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
  143. return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
  144. narg, ar.name, extramsg);
  145. }
  146. LUALIB_API int luaL_typeerror (lua_State *L, int narg, const char *tname) {
  147. const char *msg = lua_pushfstring(L, "%s expected, got %s",
  148. tname, luaL_typename(L, narg));
  149. return luaL_argerror(L, narg, msg);
  150. }
  151. static void tag_error (lua_State *L, int narg, int tag) {
  152. luaL_typeerror(L, narg, lua_typename(L, tag));
  153. }
  154. LUALIB_API void luaL_where (lua_State *L, int level) {
  155. lua_Debug ar;
  156. if (lua_getstack(L, level, &ar)) { /* check function at level */
  157. lua_getinfo(L, "Sl", &ar); /* get info about it */
  158. if (ar.currentline > 0) { /* is there info? */
  159. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  160. return;
  161. }
  162. }
  163. lua_pushliteral(L, ""); /* else, no information available... */
  164. }
  165. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  166. va_list argp;
  167. va_start(argp, fmt);
  168. luaL_where(L, 1);
  169. lua_pushvfstring(L, fmt, argp);
  170. va_end(argp);
  171. lua_concat(L, 2);
  172. return lua_error(L);
  173. }
  174. /* }====================================================== */
  175. /*
  176. ** {======================================================
  177. ** Userdata's metatable manipulation
  178. ** =======================================================
  179. */
  180. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  181. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
  182. if (!lua_isnil(L, -1)) /* name already in use? */
  183. return 0; /* leave previous value on top, but return 0 */
  184. lua_pop(L, 1);
  185. lua_newtable(L); /* create metatable */
  186. lua_pushvalue(L, -1);
  187. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  188. return 1;
  189. }
  190. LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
  191. void *p = lua_touserdata(L, ud);
  192. if (p != NULL) { /* value is a userdata? */
  193. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  194. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
  195. if (!lua_rawequal(L, -1, -2)) /* not the same? */
  196. p = NULL; /* value is a userdata with wrong metatable */
  197. lua_pop(L, 2); /* remove both metatables */
  198. return p;
  199. }
  200. }
  201. return NULL; /* value is not a userdata with a metatable */
  202. }
  203. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  204. void *p = luaL_testudata(L, ud, tname);
  205. if (p == NULL) luaL_typeerror(L, ud, tname);
  206. return p;
  207. }
  208. /* }====================================================== */
  209. /*
  210. ** {======================================================
  211. ** Argument check functions
  212. ** =======================================================
  213. */
  214. LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
  215. const char *const lst[]) {
  216. const char *name = (def) ? luaL_optstring(L, narg, def) :
  217. luaL_checkstring(L, narg);
  218. int i;
  219. for (i=0; lst[i]; i++)
  220. if (strcmp(lst[i], name) == 0)
  221. return i;
  222. return luaL_argerror(L, narg,
  223. lua_pushfstring(L, "invalid option " LUA_QS, name));
  224. }
  225. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
  226. if (!lua_checkstack(L, space)) {
  227. if (msg)
  228. luaL_error(L, "stack overflow (%s)", msg);
  229. else
  230. luaL_error(L, "stack overflow");
  231. }
  232. }
  233. LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
  234. if (lua_type(L, narg) != t)
  235. tag_error(L, narg, t);
  236. }
  237. LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  238. if (lua_type(L, narg) == LUA_TNONE)
  239. luaL_argerror(L, narg, "value expected");
  240. }
  241. LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
  242. const char *s = lua_tolstring(L, narg, len);
  243. if (!s) tag_error(L, narg, LUA_TSTRING);
  244. return s;
  245. }
  246. LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
  247. const char *def, size_t *len) {
  248. if (lua_isnoneornil(L, narg)) {
  249. if (len)
  250. *len = (def ? strlen(def) : 0);
  251. return def;
  252. }
  253. else return luaL_checklstring(L, narg, len);
  254. }
  255. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
  256. lua_Number d = lua_tonumber(L, narg);
  257. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  258. tag_error(L, narg, LUA_TNUMBER);
  259. return d;
  260. }
  261. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  262. return luaL_opt(L, luaL_checknumber, narg, def);
  263. }
  264. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  265. lua_Integer d = lua_tointeger(L, narg);
  266. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  267. tag_error(L, narg, LUA_TNUMBER);
  268. return d;
  269. }
  270. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  271. lua_Integer def) {
  272. return luaL_opt(L, luaL_checkinteger, narg, def);
  273. }
  274. /* }====================================================== */
  275. /*
  276. ** {======================================================
  277. ** Generic Buffer manipulation
  278. ** =======================================================
  279. */
  280. /*
  281. ** check whether buffer is using a userdata on the stack as a temporary
  282. ** buffer
  283. */
  284. #define buffonstack(B) ((B)->b != (B)->initb)
  285. /*
  286. ** returns a pointer to a free area with at least 'sz' bytes
  287. */
  288. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  289. lua_State *L = B->L;
  290. if (B->size - B->n < sz) { /* not enough space? */
  291. char *newbuff;
  292. size_t newsize = B->size * 2; /* double buffer size */
  293. if (newsize - B->n < sz) /* not bit enough? */
  294. newsize = B->n + sz;
  295. if (newsize < B->n || newsize - B->n < sz)
  296. luaL_error(L, "string too large");
  297. newbuff = (char *)lua_newuserdata(L, newsize); /* create larger buffer */
  298. memcpy(newbuff, B->b, B->n); /* move content to new buffer */
  299. if (buffonstack(B))
  300. lua_remove(L, -2); /* remove old buffer */
  301. B->b = newbuff;
  302. B->size = newsize;
  303. }
  304. return &B->b[B->n];
  305. }
  306. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  307. char *b = luaL_prepbuffsize(B, l);
  308. memcpy(b, s, l);
  309. luaL_addsize(B, l);
  310. }
  311. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  312. luaL_addlstring(B, s, strlen(s));
  313. }
  314. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  315. lua_State *L = B->L;
  316. lua_pushlstring(L, B->b, B->n);
  317. if (buffonstack(B))
  318. lua_remove(L, -2); /* remove old buffer */
  319. }
  320. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  321. luaL_addsize(B, sz);
  322. luaL_pushresult(B);
  323. }
  324. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  325. lua_State *L = B->L;
  326. size_t l;
  327. const char *s = lua_tolstring(L, -1, &l);
  328. if (buffonstack(B))
  329. lua_insert(L, -2); /* put value below buffer */
  330. luaL_addlstring(B, s, l);
  331. lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
  332. }
  333. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  334. B->L = L;
  335. B->b = B->initb;
  336. B->n = 0;
  337. B->size = LUAL_BUFFERSIZE;
  338. }
  339. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  340. luaL_buffinit(L, B);
  341. return luaL_prepbuffsize(B, sz);
  342. }
  343. /* }====================================================== */
  344. /*
  345. ** {======================================================
  346. ** Reference system
  347. ** =======================================================
  348. */
  349. /* number of prereserved references (for internal use) */
  350. #define FREELIST_REF (LUA_RIDX_LAST + 1) /* free list of references */
  351. LUALIB_API int luaL_ref (lua_State *L, int t) {
  352. int ref;
  353. t = abs_index(L, t);
  354. if (lua_isnil(L, -1)) {
  355. lua_pop(L, 1); /* remove from stack */
  356. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  357. }
  358. lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
  359. ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
  360. lua_pop(L, 1); /* remove it from stack */
  361. if (ref != 0) { /* any free element? */
  362. lua_rawgeti(L, t, ref); /* remove it from list */
  363. lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
  364. }
  365. else { /* no free elements */
  366. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  367. if (ref == FREELIST_REF) { /* FREELIST_REF not initialized? */
  368. lua_pushinteger(L, 0);
  369. lua_rawseti(L, t, FREELIST_REF);
  370. ref = FREELIST_REF + 1;
  371. }
  372. }
  373. lua_rawseti(L, t, ref);
  374. return ref;
  375. }
  376. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  377. if (ref >= 0) {
  378. t = abs_index(L, t);
  379. lua_rawgeti(L, t, FREELIST_REF);
  380. lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
  381. lua_pushinteger(L, ref);
  382. lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
  383. }
  384. }
  385. /* }====================================================== */
  386. /*
  387. ** {======================================================
  388. ** Load functions
  389. ** =======================================================
  390. */
  391. typedef struct LoadF {
  392. int first;
  393. FILE *f;
  394. char buff[LUAL_BUFFERSIZE];
  395. } LoadF;
  396. static const char *getF (lua_State *L, void *ud, size_t *size) {
  397. LoadF *lf = (LoadF *)ud;
  398. (void)L;
  399. if (lf->first != EOF) {
  400. *size = 1;
  401. lf->buff[0] = (char)lf->first;
  402. lf->first = EOF;
  403. }
  404. else {
  405. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  406. 'getF' called 'fread', it might still wait for user input.
  407. The next check avoids this problem. */
  408. if (feof(lf->f)) return NULL;
  409. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);
  410. }
  411. return lf->buff;
  412. }
  413. static int errfile (lua_State *L, const char *what, int fnameindex) {
  414. const char *serr = strerror(errno);
  415. const char *filename = lua_tostring(L, fnameindex) + 1;
  416. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  417. lua_remove(L, fnameindex);
  418. return LUA_ERRFILE;
  419. }
  420. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  421. LoadF lf;
  422. int status, readstatus;
  423. int c;
  424. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  425. if (filename == NULL) {
  426. lua_pushliteral(L, "=stdin");
  427. lf.f = stdin;
  428. }
  429. else {
  430. lua_pushfstring(L, "@%s", filename);
  431. lf.f = fopen(filename, "r");
  432. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  433. }
  434. c = getc(lf.f);
  435. if (c == '#') { /* Unix exec. file? */
  436. while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
  437. }
  438. else if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  439. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  440. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  441. }
  442. lf.first = c; /* 'c' is the first character of the stream */
  443. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  444. readstatus = ferror(lf.f);
  445. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  446. if (readstatus) {
  447. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  448. return errfile(L, "read", fnameindex);
  449. }
  450. lua_remove(L, fnameindex);
  451. return status;
  452. }
  453. typedef struct LoadS {
  454. const char *s;
  455. size_t size;
  456. } LoadS;
  457. static const char *getS (lua_State *L, void *ud, size_t *size) {
  458. LoadS *ls = (LoadS *)ud;
  459. (void)L;
  460. if (ls->size == 0) return NULL;
  461. *size = ls->size;
  462. ls->size = 0;
  463. return ls->s;
  464. }
  465. LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
  466. const char *name) {
  467. LoadS ls;
  468. ls.s = buff;
  469. ls.size = size;
  470. return lua_load(L, getS, &ls, name);
  471. }
  472. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  473. return luaL_loadbuffer(L, s, strlen(s), s);
  474. }
  475. /* }====================================================== */
  476. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  477. if (!lua_getmetatable(L, obj)) /* no metatable? */
  478. return 0;
  479. lua_pushstring(L, event);
  480. lua_rawget(L, -2);
  481. if (lua_isnil(L, -1)) {
  482. lua_pop(L, 2); /* remove metatable and metafield */
  483. return 0;
  484. }
  485. else {
  486. lua_remove(L, -2); /* remove only metatable */
  487. return 1;
  488. }
  489. }
  490. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  491. obj = abs_index(L, obj);
  492. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  493. return 0;
  494. lua_pushvalue(L, obj);
  495. lua_call(L, 1, 1);
  496. return 1;
  497. }
  498. LUALIB_API int luaL_len (lua_State *L, int idx) {
  499. int l;
  500. lua_len(L, idx);
  501. l = lua_tointeger(L, -1);
  502. if (l == 0 && !lua_isnumber(L, -1))
  503. luaL_error(L, "object length is not a number");
  504. lua_pop(L, 1); /* remove object */
  505. return l;
  506. }
  507. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  508. if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
  509. switch (lua_type(L, idx)) {
  510. case LUA_TNUMBER:
  511. case LUA_TSTRING:
  512. lua_pushvalue(L, idx);
  513. break;
  514. case LUA_TBOOLEAN:
  515. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  516. break;
  517. case LUA_TNIL:
  518. lua_pushliteral(L, "nil");
  519. break;
  520. default:
  521. lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
  522. lua_topointer(L, idx));
  523. break;
  524. }
  525. }
  526. return lua_tolstring(L, -1, len);
  527. }
  528. static int libsize (const luaL_Reg *l) {
  529. int size = 0;
  530. for (; l && l->name; l++) size++;
  531. return size;
  532. }
  533. LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
  534. const luaL_Reg *l, int nup) {
  535. luaL_checkversion(L);
  536. if (libname) {
  537. /* check whether lib already exists */
  538. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
  539. lua_getfield(L, -1, libname); /* get _LOADED[libname] */
  540. if (!lua_istable(L, -1)) { /* not found? */
  541. lua_pop(L, 1); /* remove previous result */
  542. /* try global variable (and create one if it does not exist) */
  543. lua_pushglobaltable(L);
  544. if (luaL_findtable(L, 0, libname, libsize(l)) != NULL)
  545. luaL_error(L, "name conflict for module " LUA_QS, libname);
  546. lua_pushvalue(L, -1);
  547. lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
  548. }
  549. lua_remove(L, -2); /* remove _LOADED table */
  550. lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
  551. }
  552. luaL_checkstack(L, nup, "too many upvalues");
  553. for (; l && l->name; l++) { /* else fill the table with given functions */
  554. int i;
  555. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  556. lua_pushvalue(L, -nup);
  557. lua_pushcclosure(L, l->func, nup);
  558. lua_setfield(L, -(nup + 2), l->name);
  559. }
  560. lua_pop(L, nup); /* remove upvalues */
  561. }
  562. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  563. const char *r) {
  564. const char *wild;
  565. size_t l = strlen(p);
  566. luaL_Buffer b;
  567. luaL_buffinit(L, &b);
  568. while ((wild = strstr(s, p)) != NULL) {
  569. luaL_addlstring(&b, s, wild - s); /* push prefix */
  570. luaL_addstring(&b, r); /* push replacement in place of pattern */
  571. s = wild + l; /* continue after `p' */
  572. }
  573. luaL_addstring(&b, s); /* push last suffix */
  574. luaL_pushresult(&b);
  575. return lua_tostring(L, -1);
  576. }
  577. LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
  578. const char *fname, int szhint) {
  579. const char *e;
  580. if (idx) lua_pushvalue(L, idx);
  581. do {
  582. e = strchr(fname, '.');
  583. if (e == NULL) e = fname + strlen(fname);
  584. lua_pushlstring(L, fname, e - fname);
  585. lua_rawget(L, -2);
  586. if (lua_isnil(L, -1)) { /* no such field? */
  587. lua_pop(L, 1); /* remove this nil */
  588. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  589. lua_pushlstring(L, fname, e - fname);
  590. lua_pushvalue(L, -2);
  591. lua_settable(L, -4); /* set new table into field */
  592. }
  593. else if (!lua_istable(L, -1)) { /* field has a non-table value? */
  594. lua_pop(L, 2); /* remove table and value */
  595. return fname; /* return problematic part of the name */
  596. }
  597. lua_remove(L, -2); /* remove previous table */
  598. fname = e + 1;
  599. } while (*e == '.');
  600. return NULL;
  601. }
  602. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  603. (void)ud;
  604. (void)osize;
  605. if (nsize == 0) {
  606. free(ptr);
  607. return NULL;
  608. }
  609. else
  610. return realloc(ptr, nsize);
  611. }
  612. static int panic (lua_State *L) {
  613. luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  614. lua_tostring(L, -1));
  615. return 0; /* return to Lua to abort */
  616. }
  617. LUALIB_API lua_State *luaL_newstate (void) {
  618. lua_State *L = lua_newstate(l_alloc, NULL);
  619. if (L) lua_atpanic(L, &panic);
  620. return L;
  621. }
  622. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
  623. const lua_Number *v = lua_version(L);
  624. if (v != lua_version(NULL))
  625. luaL_error(L, "multiple Lua VMs detected");
  626. else if (*v != ver)
  627. luaL_error(L, "version mismatch: app. needs %d, Lua core provides %f",
  628. ver, *v);
  629. }