lauxlib.c 25 KB

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