lauxlib.c 22 KB

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