Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

962 rindas
27 KiB

  1. /*
  2. ** $Id: lauxlib.c,v 1.244 2012/05/31 20:28:45 roberto Exp $
  3. ** Auxiliary functions for building Lua libraries
  4. ** See Copyright Notice in lua.h
  5. */
  6. #if defined HAVE_CONFIG_H // LOL BEGIN
  7. # include "config.h"
  8. #endif // LOL END
  9. #include <errno.h>
  10. #include <stdarg.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. /* This file uses only the official API of Lua.
  15. ** Any function declared here could be written as an application function.
  16. */
  17. #define lauxlib_c
  18. #define LUA_LIB
  19. #include "lua.h"
  20. #include "lauxlib.h"
  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. if (level == 0 || !lua_istable(L, -1))
  34. return 0; /* not found */
  35. lua_pushnil(L); /* start 'next' loop */
  36. while (lua_next(L, -2)) { /* for each pair in table */
  37. if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
  38. if (lua_rawequal(L, objidx, -1)) { /* found object? */
  39. lua_pop(L, 1); /* remove value (but keep name) */
  40. return 1;
  41. }
  42. else if (findfield(L, objidx, level - 1)) { /* try recursively */
  43. lua_remove(L, -2); /* remove table (but keep name) */
  44. lua_pushliteral(L, ".");
  45. lua_insert(L, -2); /* place '.' between the two names */
  46. lua_concat(L, 3);
  47. return 1;
  48. }
  49. }
  50. lua_pop(L, 1); /* remove value */
  51. }
  52. return 0; /* not found */
  53. }
  54. static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
  55. int top = lua_gettop(L);
  56. lua_getinfo(L, "f", ar); /* push function */
  57. lua_pushglobaltable(L);
  58. if (findfield(L, top + 1, 2)) {
  59. lua_copy(L, -1, top + 1); /* move name to proper place */
  60. lua_pop(L, 2); /* remove pushed values */
  61. return 1;
  62. }
  63. else {
  64. lua_settop(L, top); /* remove function and global table */
  65. return 0;
  66. }
  67. }
  68. static void pushfuncname (lua_State *L, lua_Debug *ar) {
  69. if (*ar->namewhat != '\0') /* is there a name? */
  70. lua_pushfstring(L, "function " LUA_QS, ar->name);
  71. else if (*ar->what == 'm') /* main? */
  72. lua_pushfstring(L, "main chunk");
  73. else if (*ar->what == 'C') {
  74. if (pushglobalfuncname(L, ar)) {
  75. lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
  76. lua_remove(L, -2); /* remove name */
  77. }
  78. else
  79. lua_pushliteral(L, "?");
  80. }
  81. else
  82. lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
  83. }
  84. static int countlevels (lua_State *L) {
  85. lua_Debug ar;
  86. int li = 1, le = 1;
  87. /* find an upper bound */
  88. while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
  89. /* do a binary search */
  90. while (li < le) {
  91. int m = (li + le)/2;
  92. if (lua_getstack(L, m, &ar)) li = m + 1;
  93. else le = m;
  94. }
  95. return le - 1;
  96. }
  97. LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
  98. const char *msg, int level) {
  99. lua_Debug ar;
  100. int top = lua_gettop(L);
  101. int numlevels = countlevels(L1);
  102. int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;
  103. if (msg) lua_pushfstring(L, "%s\n", msg);
  104. lua_pushliteral(L, "stack traceback:");
  105. while (lua_getstack(L1, level++, &ar)) {
  106. if (level == mark) { /* too many levels? */
  107. lua_pushliteral(L, "\n\t..."); /* add a '...' */
  108. level = numlevels - LEVELS2; /* and skip to last ones */
  109. }
  110. else {
  111. lua_getinfo(L1, "Slnt", &ar);
  112. lua_pushfstring(L, "\n\t%s:", ar.short_src);
  113. if (ar.currentline > 0)
  114. lua_pushfstring(L, "%d:", ar.currentline);
  115. lua_pushliteral(L, " in ");
  116. pushfuncname(L, &ar);
  117. if (ar.istailcall)
  118. lua_pushliteral(L, "\n\t(...tail calls...)");
  119. lua_concat(L, lua_gettop(L) - top);
  120. }
  121. }
  122. lua_concat(L, lua_gettop(L) - top);
  123. }
  124. /* }====================================================== */
  125. /*
  126. ** {======================================================
  127. ** Error-report functions
  128. ** =======================================================
  129. */
  130. LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
  131. lua_Debug ar;
  132. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  133. return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
  134. lua_getinfo(L, "n", &ar);
  135. if (strcmp(ar.namewhat, "method") == 0) {
  136. narg--; /* do not count `self' */
  137. if (narg == 0) /* error is in the self argument itself? */
  138. return luaL_error(L, "calling " LUA_QS " on bad self", ar.name);
  139. }
  140. if (ar.name == NULL)
  141. ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
  142. return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
  143. narg, ar.name, extramsg);
  144. }
  145. static int typeerror (lua_State *L, int narg, const char *tname) {
  146. const char *msg = lua_pushfstring(L, "%s expected, got %s",
  147. tname, luaL_typename(L, narg));
  148. return luaL_argerror(L, narg, msg);
  149. }
  150. static void tag_error (lua_State *L, int narg, int tag) {
  151. typeerror(L, narg, lua_typename(L, tag));
  152. }
  153. LUALIB_API void luaL_where (lua_State *L, int level) {
  154. lua_Debug ar;
  155. if (lua_getstack(L, level, &ar)) { /* check function at level */
  156. lua_getinfo(L, "Sl", &ar); /* get info about it */
  157. if (ar.currentline > 0) { /* is there info? */
  158. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  159. return;
  160. }
  161. }
  162. lua_pushliteral(L, ""); /* else, no information available... */
  163. }
  164. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  165. va_list argp;
  166. va_start(argp, fmt);
  167. luaL_where(L, 1);
  168. lua_pushvfstring(L, fmt, argp);
  169. va_end(argp);
  170. lua_concat(L, 2);
  171. return lua_error(L);
  172. }
  173. LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
  174. int en = errno; /* calls to Lua API may change this value */
  175. if (stat) {
  176. lua_pushboolean(L, 1);
  177. return 1;
  178. }
  179. else {
  180. lua_pushnil(L);
  181. if (fname)
  182. lua_pushfstring(L, "%s: %s", fname, strerror(en));
  183. else
  184. lua_pushfstring(L, "%s", strerror(en));
  185. lua_pushinteger(L, en);
  186. return 3;
  187. }
  188. }
  189. #if !defined(inspectstat) /* { */
  190. #if defined(LUA_USE_POSIX)
  191. #include <sys/wait.h>
  192. /*
  193. ** use appropriate macros to interpret 'pclose' return status
  194. */
  195. #define inspectstat(stat,what) \
  196. if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
  197. else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
  198. #else
  199. #define inspectstat(stat,what) /* no op */
  200. #endif
  201. #endif /* } */
  202. LUALIB_API int luaL_execresult (lua_State *L, int stat) {
  203. const char *what = "exit"; /* type of termination */
  204. if (stat == -1) /* error? */
  205. return luaL_fileresult(L, 0, NULL);
  206. else {
  207. inspectstat(stat, what); /* interpret result */
  208. if (*what == 'e' && stat == 0) /* successful termination? */
  209. lua_pushboolean(L, 1);
  210. else
  211. lua_pushnil(L);
  212. lua_pushstring(L, what);
  213. lua_pushinteger(L, stat);
  214. return 3; /* return true/nil,what,code */
  215. }
  216. }
  217. /* }====================================================== */
  218. /*
  219. ** {======================================================
  220. ** Userdata's metatable manipulation
  221. ** =======================================================
  222. */
  223. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  224. luaL_getmetatable(L, tname); /* try to get metatable */
  225. if (!lua_isnil(L, -1)) /* name already in use? */
  226. return 0; /* leave previous value on top, but return 0 */
  227. lua_pop(L, 1);
  228. lua_newtable(L); /* create metatable */
  229. lua_pushvalue(L, -1);
  230. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  231. return 1;
  232. }
  233. LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
  234. luaL_getmetatable(L, tname);
  235. lua_setmetatable(L, -2);
  236. }
  237. LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
  238. void *p = lua_touserdata(L, ud);
  239. if (p != NULL) { /* value is a userdata? */
  240. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  241. luaL_getmetatable(L, tname); /* get correct metatable */
  242. if (!lua_rawequal(L, -1, -2)) /* not the same? */
  243. p = NULL; /* value is a userdata with wrong metatable */
  244. lua_pop(L, 2); /* remove both metatables */
  245. return p;
  246. }
  247. }
  248. return NULL; /* value is not a userdata with a metatable */
  249. }
  250. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  251. void *p = luaL_testudata(L, ud, tname);
  252. if (p == NULL) typeerror(L, ud, tname);
  253. return p;
  254. }
  255. /* }====================================================== */
  256. /*
  257. ** {======================================================
  258. ** Argument check functions
  259. ** =======================================================
  260. */
  261. LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
  262. const char *const lst[]) {
  263. const char *name = (def) ? luaL_optstring(L, narg, def) :
  264. luaL_checkstring(L, narg);
  265. int i;
  266. for (i=0; lst[i]; i++)
  267. if (strcmp(lst[i], name) == 0)
  268. return i;
  269. return luaL_argerror(L, narg,
  270. lua_pushfstring(L, "invalid option " LUA_QS, name));
  271. }
  272. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
  273. /* keep some extra space to run error routines, if needed */
  274. const int extra = LUA_MINSTACK;
  275. if (!lua_checkstack(L, space + extra)) {
  276. if (msg)
  277. luaL_error(L, "stack overflow (%s)", msg);
  278. else
  279. luaL_error(L, "stack overflow");
  280. }
  281. }
  282. LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
  283. if (lua_type(L, narg) != t)
  284. tag_error(L, narg, t);
  285. }
  286. LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  287. if (lua_type(L, narg) == LUA_TNONE)
  288. luaL_argerror(L, narg, "value expected");
  289. }
  290. LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
  291. const char *s = lua_tolstring(L, narg, len);
  292. if (!s) tag_error(L, narg, LUA_TSTRING);
  293. return s;
  294. }
  295. LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
  296. const char *def, size_t *len) {
  297. if (lua_isnoneornil(L, narg)) {
  298. if (len)
  299. *len = (def ? strlen(def) : 0);
  300. return def;
  301. }
  302. else return luaL_checklstring(L, narg, len);
  303. }
  304. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
  305. int isnum;
  306. lua_Number d = lua_tonumberx(L, narg, &isnum);
  307. if (!isnum)
  308. tag_error(L, narg, LUA_TNUMBER);
  309. return d;
  310. }
  311. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  312. return luaL_opt(L, luaL_checknumber, narg, def);
  313. }
  314. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  315. int isnum;
  316. lua_Integer d = lua_tointegerx(L, narg, &isnum);
  317. if (!isnum)
  318. tag_error(L, narg, LUA_TNUMBER);
  319. return d;
  320. }
  321. LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {
  322. int isnum;
  323. lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);
  324. if (!isnum)
  325. tag_error(L, narg, LUA_TNUMBER);
  326. return d;
  327. }
  328. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  329. lua_Integer def) {
  330. return luaL_opt(L, luaL_checkinteger, narg, def);
  331. }
  332. LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg,
  333. lua_Unsigned def) {
  334. return luaL_opt(L, luaL_checkunsigned, narg, def);
  335. }
  336. /* }====================================================== */
  337. /*
  338. ** {======================================================
  339. ** Generic Buffer manipulation
  340. ** =======================================================
  341. */
  342. /*
  343. ** check whether buffer is using a userdata on the stack as a temporary
  344. ** buffer
  345. */
  346. #define buffonstack(B) ((B)->b != (B)->initb)
  347. /*
  348. ** returns a pointer to a free area with at least 'sz' bytes
  349. */
  350. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  351. lua_State *L = B->L;
  352. if (B->size - B->n < sz) { /* not enough space? */
  353. char *newbuff;
  354. size_t newsize = B->size * 2; /* double buffer size */
  355. if (newsize - B->n < sz) /* not bit enough? */
  356. newsize = B->n + sz;
  357. if (newsize < B->n || newsize - B->n < sz)
  358. luaL_error(L, "buffer too large");
  359. /* create larger buffer */
  360. newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));
  361. /* move content to new buffer */
  362. memcpy(newbuff, B->b, B->n * sizeof(char));
  363. if (buffonstack(B))
  364. lua_remove(L, -2); /* remove old buffer */
  365. B->b = newbuff;
  366. B->size = newsize;
  367. }
  368. return &B->b[B->n];
  369. }
  370. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  371. char *b = luaL_prepbuffsize(B, l);
  372. memcpy(b, s, l * sizeof(char));
  373. luaL_addsize(B, l);
  374. }
  375. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  376. luaL_addlstring(B, s, strlen(s));
  377. }
  378. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  379. lua_State *L = B->L;
  380. lua_pushlstring(L, B->b, B->n);
  381. if (buffonstack(B))
  382. lua_remove(L, -2); /* remove old buffer */
  383. }
  384. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  385. luaL_addsize(B, sz);
  386. luaL_pushresult(B);
  387. }
  388. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  389. lua_State *L = B->L;
  390. size_t l;
  391. const char *s = lua_tolstring(L, -1, &l);
  392. if (buffonstack(B))
  393. lua_insert(L, -2); /* put value below buffer */
  394. luaL_addlstring(B, s, l);
  395. lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
  396. }
  397. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  398. B->L = L;
  399. B->b = B->initb;
  400. B->n = 0;
  401. B->size = LUAL_BUFFERSIZE;
  402. }
  403. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  404. luaL_buffinit(L, B);
  405. return luaL_prepbuffsize(B, sz);
  406. }
  407. /* }====================================================== */
  408. /*
  409. ** {======================================================
  410. ** Reference system
  411. ** =======================================================
  412. */
  413. /* index of free-list header */
  414. #define freelist 0
  415. LUALIB_API int luaL_ref (lua_State *L, int t) {
  416. int ref;
  417. if (lua_isnil(L, -1)) {
  418. lua_pop(L, 1); /* remove from stack */
  419. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  420. }
  421. t = lua_absindex(L, t);
  422. lua_rawgeti(L, t, freelist); /* get first free element */
  423. ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
  424. lua_pop(L, 1); /* remove it from stack */
  425. if (ref != 0) { /* any free element? */
  426. lua_rawgeti(L, t, ref); /* remove it from list */
  427. lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
  428. }
  429. else /* no free elements */
  430. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  431. lua_rawseti(L, t, ref);
  432. return ref;
  433. }
  434. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  435. if (ref >= 0) {
  436. t = lua_absindex(L, t);
  437. lua_rawgeti(L, t, freelist);
  438. lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
  439. lua_pushinteger(L, ref);
  440. lua_rawseti(L, t, freelist); /* t[freelist] = ref */
  441. }
  442. }
  443. /* }====================================================== */
  444. /*
  445. ** {======================================================
  446. ** Load functions
  447. ** =======================================================
  448. */
  449. typedef struct LoadF {
  450. int n; /* number of pre-read characters */
  451. FILE *f; /* file being read */
  452. char buff[LUAL_BUFFERSIZE]; /* area for reading file */
  453. } LoadF;
  454. static const char *getF (lua_State *L, void *ud, size_t *size) {
  455. LoadF *lf = (LoadF *)ud;
  456. (void)L; /* not used */
  457. if (lf->n > 0) { /* are there pre-read characters to be read? */
  458. *size = lf->n; /* return them (chars already in buffer) */
  459. lf->n = 0; /* no more pre-read characters */
  460. }
  461. else { /* read a block from file */
  462. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  463. 'getF' called 'fread', it might still wait for user input.
  464. The next check avoids this problem. */
  465. if (feof(lf->f)) return NULL;
  466. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  467. }
  468. return lf->buff;
  469. }
  470. static int errfile (lua_State *L, const char *what, int fnameindex) {
  471. const char *serr = strerror(errno);
  472. const char *filename = lua_tostring(L, fnameindex) + 1;
  473. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  474. lua_remove(L, fnameindex);
  475. return LUA_ERRFILE;
  476. }
  477. static int skipBOM (LoadF *lf) {
  478. const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */
  479. int c;
  480. lf->n = 0;
  481. do {
  482. c = getc(lf->f);
  483. if (c == EOF || c != *(unsigned char *)p++) return c;
  484. lf->buff[lf->n++] = c; /* to be read by the parser */
  485. } while (*p != '\0');
  486. lf->n = 0; /* prefix matched; discard it */
  487. return getc(lf->f); /* return next character */
  488. }
  489. /*
  490. ** reads the first character of file 'f' and skips an optional BOM mark
  491. ** in its beginning plus its first line if it starts with '#'. Returns
  492. ** true if it skipped the first line. In any case, '*cp' has the
  493. ** first "valid" character of the file (after the optional BOM and
  494. ** a first-line comment).
  495. */
  496. static int skipcomment (LoadF *lf, int *cp) {
  497. int c = *cp = skipBOM(lf);
  498. if (c == '#') { /* first line is a comment (Unix exec. file)? */
  499. do { /* skip first line */
  500. c = getc(lf->f);
  501. } while (c != EOF && c != '\n') ;
  502. *cp = getc(lf->f); /* skip end-of-line, if present */
  503. return 1; /* there was a comment */
  504. }
  505. else return 0; /* no comment */
  506. }
  507. LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
  508. const char *mode) {
  509. LoadF lf;
  510. int status, readstatus;
  511. int c;
  512. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  513. if (filename == NULL) {
  514. lua_pushliteral(L, "=stdin");
  515. lf.f = stdin;
  516. }
  517. else {
  518. lua_pushfstring(L, "@%s", filename);
  519. lf.f = fopen(filename, "r");
  520. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  521. }
  522. if (skipcomment(&lf, &c)) /* read initial portion */
  523. lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
  524. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  525. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  526. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  527. skipcomment(&lf, &c); /* re-read initial portion */
  528. }
  529. if (c != EOF)
  530. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  531. status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
  532. readstatus = ferror(lf.f);
  533. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  534. if (readstatus) {
  535. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  536. return errfile(L, "read", fnameindex);
  537. }
  538. lua_remove(L, fnameindex);
  539. return status;
  540. }
  541. typedef struct LoadS {
  542. const char *s;
  543. size_t size;
  544. } LoadS;
  545. static const char *getS (lua_State *L, void *ud, size_t *size) {
  546. LoadS *ls = (LoadS *)ud;
  547. (void)L; /* not used */
  548. if (ls->size == 0) return NULL;
  549. *size = ls->size;
  550. ls->size = 0;
  551. return ls->s;
  552. }
  553. LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
  554. const char *name, const char *mode) {
  555. LoadS ls;
  556. ls.s = buff;
  557. ls.size = size;
  558. return lua_load(L, getS, &ls, name, mode);
  559. }
  560. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  561. return luaL_loadbuffer(L, s, strlen(s), s);
  562. }
  563. /* }====================================================== */
  564. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  565. if (!lua_getmetatable(L, obj)) /* no metatable? */
  566. return 0;
  567. lua_pushstring(L, event);
  568. lua_rawget(L, -2);
  569. if (lua_isnil(L, -1)) {
  570. lua_pop(L, 2); /* remove metatable and metafield */
  571. return 0;
  572. }
  573. else {
  574. lua_remove(L, -2); /* remove only metatable */
  575. return 1;
  576. }
  577. }
  578. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  579. obj = lua_absindex(L, obj);
  580. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  581. return 0;
  582. lua_pushvalue(L, obj);
  583. lua_call(L, 1, 1);
  584. return 1;
  585. }
  586. LUALIB_API int luaL_len (lua_State *L, int idx) {
  587. int l;
  588. int isnum;
  589. lua_len(L, idx);
  590. l = (int)lua_tointegerx(L, -1, &isnum);
  591. if (!isnum)
  592. luaL_error(L, "object length is not a number");
  593. lua_pop(L, 1); /* remove object */
  594. return l;
  595. }
  596. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  597. if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
  598. switch (lua_type(L, idx)) {
  599. case LUA_TNUMBER:
  600. case LUA_TSTRING:
  601. lua_pushvalue(L, idx);
  602. break;
  603. case LUA_TBOOLEAN:
  604. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  605. break;
  606. case LUA_TNIL:
  607. lua_pushliteral(L, "nil");
  608. break;
  609. default:
  610. lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
  611. lua_topointer(L, idx));
  612. break;
  613. }
  614. }
  615. return lua_tolstring(L, -1, len);
  616. }
  617. /*
  618. ** {======================================================
  619. ** Compatibility with 5.1 module functions
  620. ** =======================================================
  621. */
  622. #if defined(LUA_COMPAT_MODULE)
  623. static const char *luaL_findtable (lua_State *L, int idx,
  624. const char *fname, int szhint) {
  625. const char *e;
  626. if (idx) lua_pushvalue(L, idx);
  627. do {
  628. e = strchr(fname, '.');
  629. if (e == NULL) e = fname + strlen(fname);
  630. lua_pushlstring(L, fname, e - fname);
  631. lua_rawget(L, -2);
  632. if (lua_isnil(L, -1)) { /* no such field? */
  633. lua_pop(L, 1); /* remove this nil */
  634. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  635. lua_pushlstring(L, fname, e - fname);
  636. lua_pushvalue(L, -2);
  637. lua_settable(L, -4); /* set new table into field */
  638. }
  639. else if (!lua_istable(L, -1)) { /* field has a non-table value? */
  640. lua_pop(L, 2); /* remove table and value */
  641. return fname; /* return problematic part of the name */
  642. }
  643. lua_remove(L, -2); /* remove previous table */
  644. fname = e + 1;
  645. } while (*e == '.');
  646. return NULL;
  647. }
  648. /*
  649. ** Count number of elements in a luaL_Reg list.
  650. */
  651. static int libsize (const luaL_Reg *l) {
  652. int size = 0;
  653. for (; l && l->name; l++) size++;
  654. return size;
  655. }
  656. /*
  657. ** Find or create a module table with a given name. The function
  658. ** first looks at the _LOADED table and, if that fails, try a
  659. ** global variable with that name. In any case, leaves on the stack
  660. ** the module table.
  661. */
  662. LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
  663. int sizehint) {
  664. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
  665. lua_getfield(L, -1, modname); /* get _LOADED[modname] */
  666. if (!lua_istable(L, -1)) { /* not found? */
  667. lua_pop(L, 1); /* remove previous result */
  668. /* try global variable (and create one if it does not exist) */
  669. lua_pushglobaltable(L);
  670. if (luaL_findtable(L, 0, modname, sizehint) != NULL)
  671. luaL_error(L, "name conflict for module " LUA_QS, modname);
  672. lua_pushvalue(L, -1);
  673. lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
  674. }
  675. lua_remove(L, -2); /* remove _LOADED table */
  676. }
  677. LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
  678. const luaL_Reg *l, int nup) {
  679. luaL_checkversion(L);
  680. if (libname) {
  681. luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
  682. lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
  683. }
  684. if (l)
  685. luaL_setfuncs(L, l, nup);
  686. else
  687. lua_pop(L, nup); /* remove upvalues */
  688. }
  689. #endif
  690. /* }====================================================== */
  691. /*
  692. ** set functions from list 'l' into table at top - 'nup'; each
  693. ** function gets the 'nup' elements at the top as upvalues.
  694. ** Returns with only the table at the stack.
  695. */
  696. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  697. luaL_checkversion(L);
  698. luaL_checkstack(L, nup, "too many upvalues");
  699. for (; l->name != NULL; l++) { /* fill the table with given functions */
  700. int i;
  701. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  702. lua_pushvalue(L, -nup);
  703. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  704. lua_setfield(L, -(nup + 2), l->name);
  705. }
  706. lua_pop(L, nup); /* remove upvalues */
  707. }
  708. /*
  709. ** ensure that stack[idx][fname] has a table and push that table
  710. ** into the stack
  711. */
  712. LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
  713. lua_getfield(L, idx, fname);
  714. if (lua_istable(L, -1)) return 1; /* table already there */
  715. else {
  716. lua_pop(L, 1); /* remove previous result */
  717. idx = lua_absindex(L, idx);
  718. lua_newtable(L);
  719. lua_pushvalue(L, -1); /* copy to be left at top */
  720. lua_setfield(L, idx, fname); /* assign new table to field */
  721. return 0; /* false, because did not find table there */
  722. }
  723. }
  724. /*
  725. ** stripped-down 'require'. Calls 'openf' to open a module,
  726. ** registers the result in 'package.loaded' table and, if 'glb'
  727. ** is true, also registers the result in the global table.
  728. ** Leaves resulting module on the top.
  729. */
  730. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  731. lua_CFunction openf, int glb) {
  732. lua_pushcfunction(L, openf);
  733. lua_pushstring(L, modname); /* argument to open function */
  734. lua_call(L, 1, 1); /* open module */
  735. luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
  736. lua_pushvalue(L, -2); /* make copy of module (call result) */
  737. lua_setfield(L, -2, modname); /* _LOADED[modname] = module */
  738. lua_pop(L, 1); /* remove _LOADED table */
  739. if (glb) {
  740. lua_pushvalue(L, -1); /* copy of 'mod' */
  741. lua_setglobal(L, modname); /* _G[modname] = module */
  742. }
  743. }
  744. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  745. const char *r) {
  746. const char *wild;
  747. size_t l = strlen(p);
  748. luaL_Buffer b;
  749. luaL_buffinit(L, &b);
  750. while ((wild = strstr(s, p)) != NULL) {
  751. luaL_addlstring(&b, s, wild - s); /* push prefix */
  752. luaL_addstring(&b, r); /* push replacement in place of pattern */
  753. s = wild + l; /* continue after `p' */
  754. }
  755. luaL_addstring(&b, s); /* push last suffix */
  756. luaL_pushresult(&b);
  757. return lua_tostring(L, -1);
  758. }
  759. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  760. (void)ud; (void)osize; /* not used */
  761. if (nsize == 0) {
  762. free(ptr);
  763. return NULL;
  764. }
  765. else
  766. return realloc(ptr, nsize);
  767. }
  768. static int panic (lua_State *L) {
  769. luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  770. lua_tostring(L, -1));
  771. return 0; /* return to Lua to abort */
  772. }
  773. LUALIB_API lua_State *luaL_newstate (void) {
  774. lua_State *L = lua_newstate(l_alloc, NULL);
  775. if (L) lua_atpanic(L, &panic);
  776. return L;
  777. }
  778. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
  779. const lua_Number *v = lua_version(L);
  780. if (v != lua_version(NULL))
  781. luaL_error(L, "multiple Lua VMs detected");
  782. else if (*v != ver)
  783. luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
  784. ver, *v);
  785. /* check conversions number -> integer types */
  786. lua_pushnumber(L, -(lua_Number)0x1234);
  787. if (lua_tointeger(L, -1) != -0x1234 ||
  788. lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234)
  789. luaL_error(L, "bad conversion number->int;"
  790. " must recompile Lua with proper settings");
  791. lua_pop(L, 1);
  792. }