You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1039 lines
30 KiB

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