lauxlib.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. /*
  2. ** $Id: lauxlib.c,v 1.220 2010/08/03 20:21:16 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. int isnum;
  254. lua_Number d = lua_tonumberx(L, narg, &isnum);
  255. if (!isnum)
  256. tag_error(L, narg, LUA_TNUMBER);
  257. return d;
  258. }
  259. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  260. return luaL_opt(L, luaL_checknumber, narg, def);
  261. }
  262. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  263. int isnum;
  264. lua_Integer d = lua_tointegerx(L, narg, &isnum);
  265. if (!isnum)
  266. tag_error(L, narg, LUA_TNUMBER);
  267. return d;
  268. }
  269. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  270. lua_Integer def) {
  271. return luaL_opt(L, luaL_checkinteger, narg, def);
  272. }
  273. /* }====================================================== */
  274. /*
  275. ** {======================================================
  276. ** Generic Buffer manipulation
  277. ** =======================================================
  278. */
  279. /*
  280. ** check whether buffer is using a userdata on the stack as a temporary
  281. ** buffer
  282. */
  283. #define buffonstack(B) ((B)->b != (B)->initb)
  284. /*
  285. ** returns a pointer to a free area with at least 'sz' bytes
  286. */
  287. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  288. lua_State *L = B->L;
  289. if (B->size - B->n < sz) { /* not enough space? */
  290. char *newbuff;
  291. size_t newsize = B->size * 2; /* double buffer size */
  292. if (newsize - B->n < sz) /* not bit enough? */
  293. newsize = B->n + sz;
  294. if (newsize < B->n || newsize - B->n < sz)
  295. luaL_error(L, "string too large");
  296. newbuff = (char *)lua_newuserdata(L, newsize); /* create larger buffer */
  297. memcpy(newbuff, B->b, B->n); /* move content to new buffer */
  298. if (buffonstack(B))
  299. lua_remove(L, -2); /* remove old buffer */
  300. B->b = newbuff;
  301. B->size = newsize;
  302. }
  303. return &B->b[B->n];
  304. }
  305. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  306. char *b = luaL_prepbuffsize(B, l);
  307. memcpy(b, s, l);
  308. luaL_addsize(B, l);
  309. }
  310. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  311. luaL_addlstring(B, s, strlen(s));
  312. }
  313. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  314. lua_State *L = B->L;
  315. lua_pushlstring(L, B->b, B->n);
  316. if (buffonstack(B))
  317. lua_remove(L, -2); /* remove old buffer */
  318. }
  319. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  320. luaL_addsize(B, sz);
  321. luaL_pushresult(B);
  322. }
  323. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  324. lua_State *L = B->L;
  325. size_t l;
  326. const char *s = lua_tolstring(L, -1, &l);
  327. if (buffonstack(B))
  328. lua_insert(L, -2); /* put value below buffer */
  329. luaL_addlstring(B, s, l);
  330. lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
  331. }
  332. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  333. B->L = L;
  334. B->b = B->initb;
  335. B->n = 0;
  336. B->size = LUAL_BUFFERSIZE;
  337. }
  338. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  339. luaL_buffinit(L, B);
  340. return luaL_prepbuffsize(B, sz);
  341. }
  342. /* }====================================================== */
  343. /*
  344. ** {======================================================
  345. ** Reference system
  346. ** =======================================================
  347. */
  348. /* index of free-list header */
  349. #define freelist 0
  350. LUALIB_API int luaL_ref (lua_State *L, int t) {
  351. int ref;
  352. t = lua_absindex(L, t);
  353. if (lua_isnil(L, -1)) {
  354. lua_pop(L, 1); /* remove from stack */
  355. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  356. }
  357. lua_rawgeti(L, t, freelist); /* get first free element */
  358. ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
  359. lua_pop(L, 1); /* remove it from stack */
  360. if (ref != 0) { /* any free element? */
  361. lua_rawgeti(L, t, ref); /* remove it from list */
  362. lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
  363. }
  364. else /* no free elements */
  365. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  366. lua_rawseti(L, t, ref);
  367. return ref;
  368. }
  369. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  370. if (ref >= 0) {
  371. t = lua_absindex(L, t);
  372. lua_rawgeti(L, t, freelist);
  373. lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
  374. lua_pushinteger(L, ref);
  375. lua_rawseti(L, t, freelist); /* t[freelist] = ref */
  376. }
  377. }
  378. /* }====================================================== */
  379. /*
  380. ** {======================================================
  381. ** Load functions
  382. ** =======================================================
  383. */
  384. typedef struct LoadF {
  385. int n; /* number of pre-read characters */
  386. FILE *f; /* file being read */
  387. char buff[LUAL_BUFFERSIZE]; /* area for reading file */
  388. } LoadF;
  389. static const char *getF (lua_State *L, void *ud, size_t *size) {
  390. LoadF *lf = (LoadF *)ud;
  391. (void)L;
  392. if (lf->n > 0) { /* are there pre-read characters to be read? */
  393. *size = lf->n; /* return them (chars already in buffer) */
  394. lf->n = 0; /* no more pre-read characters */
  395. }
  396. else { /* read a block from file */
  397. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  398. 'getF' called 'fread', it might still wait for user input.
  399. The next check avoids this problem. */
  400. if (feof(lf->f)) return NULL;
  401. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  402. }
  403. return lf->buff;
  404. }
  405. static int errfile (lua_State *L, const char *what, int fnameindex) {
  406. const char *serr = strerror(errno);
  407. const char *filename = lua_tostring(L, fnameindex) + 1;
  408. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  409. lua_remove(L, fnameindex);
  410. return LUA_ERRFILE;
  411. }
  412. static int skipBOM (LoadF *lf) {
  413. const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */
  414. int c;
  415. lf->n = 0;
  416. do {
  417. c = getc(lf->f);
  418. if (c == EOF || c != *(unsigned char *)p++) return c;
  419. lf->buff[lf->n++] = c; /* to be read by the parser */
  420. } while (*p != '\0');
  421. lf->n = 0; /* prefix matched; discard it */
  422. return getc(lf->f); /* return next character */
  423. }
  424. /*
  425. ** reads the first character of file 'f' and skips an optional BOM mark
  426. ** in its beginning plus its first line if it starts with '#'. Returns
  427. ** true if it skipped the first line. In any case, '*cp' has the
  428. ** first "valid" character of the file (after the optional BOM and
  429. ** a first-line comment).
  430. */
  431. static int skipcomment (LoadF *lf, int *cp) {
  432. int c = *cp = skipBOM(lf);
  433. if (c == '#') { /* first line is a comment (Unix exec. file)? */
  434. while ((c = getc(lf->f)) != EOF && c != '\n') ; /* skip first line */
  435. *cp = getc(lf->f); /* skip end-of-line */
  436. return 1; /* there was a comment */
  437. }
  438. else return 0; /* no comment */
  439. }
  440. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  441. LoadF lf;
  442. int status, readstatus;
  443. int c;
  444. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  445. if (filename == NULL) {
  446. lua_pushliteral(L, "=stdin");
  447. lf.f = stdin;
  448. }
  449. else {
  450. lua_pushfstring(L, "@%s", filename);
  451. lf.f = fopen(filename, "r");
  452. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  453. }
  454. if (skipcomment(&lf, &c)) /* read initial portion */
  455. lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
  456. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  457. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  458. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  459. skipcomment(&lf, &c); /* re-read initial portion */
  460. }
  461. if (c != EOF)
  462. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  463. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  464. readstatus = ferror(lf.f);
  465. if (filename) 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. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  497. if (!lua_getmetatable(L, obj)) /* no metatable? */
  498. return 0;
  499. lua_pushstring(L, event);
  500. lua_rawget(L, -2);
  501. if (lua_isnil(L, -1)) {
  502. lua_pop(L, 2); /* remove metatable and metafield */
  503. return 0;
  504. }
  505. else {
  506. lua_remove(L, -2); /* remove only metatable */
  507. return 1;
  508. }
  509. }
  510. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  511. obj = lua_absindex(L, obj);
  512. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  513. return 0;
  514. lua_pushvalue(L, obj);
  515. lua_call(L, 1, 1);
  516. return 1;
  517. }
  518. LUALIB_API int luaL_len (lua_State *L, int idx) {
  519. int l;
  520. int isnum;
  521. lua_len(L, idx);
  522. l = lua_tointegerx(L, -1, &isnum);
  523. if (!isnum)
  524. luaL_error(L, "object length is not a number");
  525. lua_pop(L, 1); /* remove object */
  526. return l;
  527. }
  528. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  529. if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
  530. switch (lua_type(L, idx)) {
  531. case LUA_TNUMBER:
  532. case LUA_TSTRING:
  533. lua_pushvalue(L, idx);
  534. break;
  535. case LUA_TBOOLEAN:
  536. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  537. break;
  538. case LUA_TNIL:
  539. lua_pushliteral(L, "nil");
  540. break;
  541. default:
  542. lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
  543. lua_topointer(L, idx));
  544. break;
  545. }
  546. }
  547. return lua_tolstring(L, -1, len);
  548. }
  549. /*
  550. ** {======================================================
  551. ** Compatibility with 5.1 module functions
  552. ** =======================================================
  553. */
  554. #if defined(LUA_COMPAT_MODULE)
  555. static const char *luaL_findtablex (lua_State *L, int idx,
  556. const char *fname, int szhint) {
  557. const char *e;
  558. if (idx) lua_pushvalue(L, idx);
  559. do {
  560. e = strchr(fname, '.');
  561. if (e == NULL) e = fname + strlen(fname);
  562. lua_pushlstring(L, fname, e - fname);
  563. lua_rawget(L, -2);
  564. if (lua_isnil(L, -1)) { /* no such field? */
  565. lua_pop(L, 1); /* remove this nil */
  566. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  567. lua_pushlstring(L, fname, e - fname);
  568. lua_pushvalue(L, -2);
  569. lua_settable(L, -4); /* set new table into field */
  570. }
  571. else if (!lua_istable(L, -1)) { /* field has a non-table value? */
  572. lua_pop(L, 2); /* remove table and value */
  573. return fname; /* return problematic part of the name */
  574. }
  575. lua_remove(L, -2); /* remove previous table */
  576. fname = e + 1;
  577. } while (*e == '.');
  578. return NULL;
  579. }
  580. /*
  581. ** Count number of elements in a luaL_Reg list.
  582. */
  583. static int libsize (const luaL_Reg *l) {
  584. int size = 0;
  585. for (; l && l->name; l++) size++;
  586. return size;
  587. }
  588. /*
  589. ** Find or create a module table with a given name. The function
  590. ** first looks at the _LOADED table and, if that fails, try a
  591. ** global variable with that name. In any case, leaves on the stack
  592. ** the module table.
  593. */
  594. LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
  595. int sizehint) {
  596. luaL_findtablex(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
  597. lua_getfield(L, -1, modname); /* get _LOADED[modname] */
  598. if (!lua_istable(L, -1)) { /* not found? */
  599. lua_pop(L, 1); /* remove previous result */
  600. /* try global variable (and create one if it does not exist) */
  601. lua_pushglobaltable(L);
  602. if (luaL_findtablex(L, 0, modname, sizehint) != NULL)
  603. luaL_error(L, "name conflict for module " LUA_QS, modname);
  604. lua_pushvalue(L, -1);
  605. lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
  606. }
  607. lua_remove(L, -2); /* remove _LOADED table */
  608. }
  609. LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
  610. const luaL_Reg *l, int nup) {
  611. luaL_checkversion(L);
  612. if (libname) {
  613. luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
  614. lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
  615. }
  616. luaL_setfuncs(L, l, nup);
  617. }
  618. #endif
  619. /* }====================================================== */
  620. /*
  621. ** set functions from list 'l' into table at top - 'nup'; each
  622. ** function gets the 'nup' elements at the top as upvalues.
  623. ** Returns with only the table at the stack.
  624. */
  625. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  626. luaL_checkstack(L, nup, "too many upvalues");
  627. for (; l && l->name; l++) { /* fill the table with given functions */
  628. int i;
  629. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  630. lua_pushvalue(L, -nup);
  631. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  632. lua_setfield(L, -(nup + 2), l->name);
  633. }
  634. lua_pop(L, nup); /* remove upvalues */
  635. }
  636. /*
  637. ** ensure that stack[idx][fname] has a table and push that table
  638. ** into the stack
  639. */
  640. LUALIB_API void luaL_findtable (lua_State *L, int idx, const char *fname) {
  641. lua_getfield(L, idx, fname);
  642. if (lua_istable(L, -1)) return; /* table already there */
  643. else {
  644. idx = lua_absindex(L, idx);
  645. lua_pop(L, 1); /* remove previous result */
  646. lua_newtable(L);
  647. lua_pushvalue(L, -1); /* copy to be left at top */
  648. lua_setfield(L, idx, fname); /* assign new table to field */
  649. }
  650. }
  651. /*
  652. ** stripped-down 'require'. Calls 'openf' to open a module,
  653. ** registers the result in 'package.loaded' table and, if 'glb'
  654. ** is true, also registers the result in the global table.
  655. ** Leaves resulting module on the top.
  656. */
  657. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  658. lua_CFunction openf, int glb) {
  659. lua_pushcfunction(L, openf);
  660. lua_pushstring(L, modname); /* argument to open function */
  661. lua_call(L, 1, 1); /* open module */
  662. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED");
  663. lua_pushvalue(L, -2); /* make copy of module (call result) */
  664. lua_setfield(L, -2, modname); /* _LOADED[modname] = module */
  665. lua_pop(L, 1); /* remove _LOADED table */
  666. if (glb) {
  667. lua_pushglobaltable(L);
  668. lua_pushvalue(L, -2); /* copy of 'mod' */
  669. lua_setfield(L, -2, modname); /* _G[modname] = module */
  670. lua_pop(L, 1); /* remove _G table */
  671. }
  672. }
  673. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  674. const char *r) {
  675. const char *wild;
  676. size_t l = strlen(p);
  677. luaL_Buffer b;
  678. luaL_buffinit(L, &b);
  679. while ((wild = strstr(s, p)) != NULL) {
  680. luaL_addlstring(&b, s, wild - s); /* push prefix */
  681. luaL_addstring(&b, r); /* push replacement in place of pattern */
  682. s = wild + l; /* continue after `p' */
  683. }
  684. luaL_addstring(&b, s); /* push last suffix */
  685. luaL_pushresult(&b);
  686. return lua_tostring(L, -1);
  687. }
  688. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  689. (void)ud;
  690. (void)osize;
  691. if (nsize == 0) {
  692. free(ptr);
  693. return NULL;
  694. }
  695. else
  696. return realloc(ptr, nsize);
  697. }
  698. static int panic (lua_State *L) {
  699. luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  700. lua_tostring(L, -1));
  701. return 0; /* return to Lua to abort */
  702. }
  703. LUALIB_API lua_State *luaL_newstate (void) {
  704. lua_State *L = lua_newstate(l_alloc, NULL);
  705. if (L) lua_atpanic(L, &panic);
  706. return L;
  707. }
  708. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
  709. const lua_Number *v = lua_version(L);
  710. if (v != lua_version(NULL))
  711. luaL_error(L, "multiple Lua VMs detected");
  712. else if (*v != ver)
  713. luaL_error(L, "version mismatch: app. needs %d, Lua core provides %f",
  714. ver, *v);
  715. }