lauxlib.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. /*
  2. ** $Id: lauxlib.c $
  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. #include <errno.h>
  10. #include <stdarg.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. /*
  15. ** This file uses only the official API of Lua.
  16. ** Any function declared here could be written as an application function.
  17. */
  18. #include "lua.h"
  19. #include "lauxlib.h"
  20. #if !defined(MAX_SIZET)
  21. /* maximum value for size_t */
  22. #define MAX_SIZET ((size_t)(~(size_t)0))
  23. #endif
  24. /*
  25. ** {======================================================
  26. ** Traceback
  27. ** =======================================================
  28. */
  29. #define LEVELS1 10 /* size of the first part of the stack */
  30. #define LEVELS2 11 /* size of the second part of the stack */
  31. /*
  32. ** search for 'objidx' in table at index -1.
  33. ** return 1 + string at top if find a good name.
  34. */
  35. static int findfield (lua_State *L, int objidx, int level) {
  36. if (level == 0 || !lua_istable(L, -1))
  37. return 0; /* not found */
  38. lua_pushnil(L); /* start 'next' loop */
  39. while (lua_next(L, -2)) { /* for each pair in table */
  40. if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
  41. if (lua_rawequal(L, objidx, -1)) { /* found object? */
  42. lua_pop(L, 1); /* remove value (but keep name) */
  43. return 1;
  44. }
  45. else if (findfield(L, objidx, level - 1)) { /* try recursively */
  46. lua_remove(L, -2); /* remove table (but keep name) */
  47. lua_pushliteral(L, ".");
  48. lua_insert(L, -2); /* place '.' between the two names */
  49. lua_concat(L, 3);
  50. return 1;
  51. }
  52. }
  53. lua_pop(L, 1); /* remove value */
  54. }
  55. return 0; /* not found */
  56. }
  57. /*
  58. ** Search for a name for a function in all loaded modules
  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, LUA_LOADED_TABLE);
  64. if (findfield(L, top + 1, 2)) {
  65. const char *name = lua_tostring(L, -1);
  66. if (strncmp(name, LUA_GNAME ".", 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. int luaL_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. luaL_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. luaL_argexpected(L, p != NULL, 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. luaL_error(L, "not enough memory for buffer allocation");
  384. box->box = temp;
  385. box->bsize = newsize;
  386. return temp;
  387. }
  388. static int boxgc (lua_State *L) {
  389. resizebox(L, 1, 0);
  390. return 0;
  391. }
  392. static const luaL_Reg boxmt[] = { /* box metamethods */
  393. {"__gc", boxgc},
  394. {"__close", boxgc},
  395. {NULL, NULL}
  396. };
  397. static void newbox (lua_State *L) {
  398. UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0);
  399. box->box = NULL;
  400. box->bsize = 0;
  401. if (luaL_newmetatable(L, "_UBOX*")) /* creating metatable? */
  402. luaL_setfuncs(L, boxmt, 0); /* set its metamethods */
  403. lua_setmetatable(L, -2);
  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)->init.b)
  410. /*
  411. ** Compute new size for buffer 'B', enough to accommodate extra 'sz'
  412. ** bytes.
  413. */
  414. static size_t newbuffsize (luaL_Buffer *B, size_t sz) {
  415. size_t newsize = B->size * 2; /* double buffer size */
  416. if (MAX_SIZET - sz < B->n) /* overflow in (B->n + sz)? */
  417. return luaL_error(B->L, "buffer too large");
  418. if (newsize < B->n + sz) /* double is not big enough? */
  419. newsize = B->n + sz;
  420. return newsize;
  421. }
  422. /*
  423. ** Returns a pointer to a free area with at least 'sz' bytes in buffer
  424. ** 'B'. 'boxidx' is the relative position in the stack where the
  425. ** buffer's box is or should be.
  426. */
  427. static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) {
  428. if (B->size - B->n >= sz) /* enough space? */
  429. return B->b + B->n;
  430. else {
  431. lua_State *L = B->L;
  432. char *newbuff;
  433. size_t newsize = newbuffsize(B, sz);
  434. /* create larger buffer */
  435. if (buffonstack(B)) /* buffer already has a box? */
  436. newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */
  437. else { /* no box yet */
  438. lua_pushnil(L); /* reserve slot for final result */
  439. newbox(L); /* create a new box */
  440. /* move box (and slot) to its intended position */
  441. lua_rotate(L, boxidx - 1, 2);
  442. lua_toclose(L, boxidx);
  443. newbuff = (char *)resizebox(L, boxidx, newsize);
  444. memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
  445. }
  446. B->b = newbuff;
  447. B->size = newsize;
  448. return newbuff + B->n;
  449. }
  450. }
  451. /*
  452. ** returns a pointer to a free area with at least 'sz' bytes
  453. */
  454. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  455. return prepbuffsize(B, sz, -1);
  456. }
  457. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  458. if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */
  459. char *b = prepbuffsize(B, l, -1);
  460. memcpy(b, s, l * sizeof(char));
  461. luaL_addsize(B, l);
  462. }
  463. }
  464. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  465. luaL_addlstring(B, s, strlen(s));
  466. }
  467. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  468. lua_State *L = B->L;
  469. lua_pushlstring(L, B->b, B->n);
  470. if (buffonstack(B)) {
  471. lua_copy(L, -1, -3); /* move string to reserved slot */
  472. lua_pop(L, 2); /* pop string and box (closing the box) */
  473. }
  474. }
  475. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  476. luaL_addsize(B, sz);
  477. luaL_pushresult(B);
  478. }
  479. /*
  480. ** 'luaL_addvalue' is the only function in the Buffer system where the
  481. ** box (if existent) is not on the top of the stack. So, instead of
  482. ** calling 'luaL_addlstring', it replicates the code using -2 as the
  483. ** last argument to 'prepbuffsize', signaling that the box is (or will
  484. ** be) bellow the string being added to the buffer. (Box creation can
  485. ** trigger an emergency GC, so we should not remove the string from the
  486. ** stack before we have the space guaranteed.)
  487. */
  488. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  489. lua_State *L = B->L;
  490. size_t len;
  491. const char *s = lua_tolstring(L, -1, &len);
  492. char *b = prepbuffsize(B, len, -2);
  493. memcpy(b, s, len * sizeof(char));
  494. luaL_addsize(B, len);
  495. lua_pop(L, 1); /* pop string */
  496. }
  497. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  498. B->L = L;
  499. B->b = B->init.b;
  500. B->n = 0;
  501. B->size = LUAL_BUFFERSIZE;
  502. }
  503. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  504. luaL_buffinit(L, B);
  505. return prepbuffsize(B, sz, -1);
  506. }
  507. /* }====================================================== */
  508. /*
  509. ** {======================================================
  510. ** Reference system
  511. ** =======================================================
  512. */
  513. /* index of free-list header */
  514. #define freelist 0
  515. LUALIB_API int luaL_ref (lua_State *L, int t) {
  516. int ref;
  517. if (lua_isnil(L, -1)) {
  518. lua_pop(L, 1); /* remove from stack */
  519. return LUA_REFNIL; /* 'nil' has a unique fixed reference */
  520. }
  521. t = lua_absindex(L, t);
  522. lua_rawgeti(L, t, freelist); /* get first free element */
  523. ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
  524. lua_pop(L, 1); /* remove it from stack */
  525. if (ref != 0) { /* any free element? */
  526. lua_rawgeti(L, t, ref); /* remove it from list */
  527. lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
  528. }
  529. else /* no free elements */
  530. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  531. lua_rawseti(L, t, ref);
  532. return ref;
  533. }
  534. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  535. if (ref >= 0) {
  536. t = lua_absindex(L, t);
  537. lua_rawgeti(L, t, freelist);
  538. lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
  539. lua_pushinteger(L, ref);
  540. lua_rawseti(L, t, freelist); /* t[freelist] = ref */
  541. }
  542. }
  543. /* }====================================================== */
  544. /*
  545. ** {======================================================
  546. ** Load functions
  547. ** =======================================================
  548. */
  549. typedef struct LoadF {
  550. int n; /* number of pre-read characters */
  551. FILE *f; /* file being read */
  552. char buff[BUFSIZ]; /* area for reading file */
  553. } LoadF;
  554. static const char *getF (lua_State *L, void *ud, size_t *size) {
  555. LoadF *lf = (LoadF *)ud;
  556. (void)L; /* not used */
  557. if (lf->n > 0) { /* are there pre-read characters to be read? */
  558. *size = lf->n; /* return them (chars already in buffer) */
  559. lf->n = 0; /* no more pre-read characters */
  560. }
  561. else { /* read a block from file */
  562. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  563. 'getF' called 'fread', it might still wait for user input.
  564. The next check avoids this problem. */
  565. if (feof(lf->f)) return NULL;
  566. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  567. }
  568. return lf->buff;
  569. }
  570. static int errfile (lua_State *L, const char *what, int fnameindex) {
  571. const char *serr = strerror(errno);
  572. const char *filename = lua_tostring(L, fnameindex) + 1;
  573. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  574. lua_remove(L, fnameindex);
  575. return LUA_ERRFILE;
  576. }
  577. static int skipBOM (LoadF *lf) {
  578. const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */
  579. int c;
  580. lf->n = 0;
  581. do {
  582. c = getc(lf->f);
  583. if (c == EOF || c != *(const unsigned char *)p++) return c;
  584. lf->buff[lf->n++] = c; /* to be read by the parser */
  585. } while (*p != '\0');
  586. lf->n = 0; /* prefix matched; discard it */
  587. return getc(lf->f); /* return next character */
  588. }
  589. /*
  590. ** reads the first character of file 'f' and skips an optional BOM mark
  591. ** in its beginning plus its first line if it starts with '#'. Returns
  592. ** true if it skipped the first line. In any case, '*cp' has the
  593. ** first "valid" character of the file (after the optional BOM and
  594. ** a first-line comment).
  595. */
  596. static int skipcomment (LoadF *lf, int *cp) {
  597. int c = *cp = skipBOM(lf);
  598. if (c == '#') { /* first line is a comment (Unix exec. file)? */
  599. do { /* skip first line */
  600. c = getc(lf->f);
  601. } while (c != EOF && c != '\n');
  602. *cp = getc(lf->f); /* skip end-of-line, if present */
  603. return 1; /* there was a comment */
  604. }
  605. else return 0; /* no comment */
  606. }
  607. LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
  608. const char *mode) {
  609. LoadF lf;
  610. int status, readstatus;
  611. int c;
  612. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  613. if (filename == NULL) {
  614. lua_pushliteral(L, "=stdin");
  615. lf.f = stdin;
  616. }
  617. else {
  618. lua_pushfstring(L, "@%s", filename);
  619. lf.f = fopen(filename, "r");
  620. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  621. }
  622. if (skipcomment(&lf, &c)) /* read initial portion */
  623. lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
  624. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  625. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  626. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  627. skipcomment(&lf, &c); /* re-read initial portion */
  628. }
  629. if (c != EOF)
  630. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  631. status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
  632. readstatus = ferror(lf.f);
  633. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  634. if (readstatus) {
  635. lua_settop(L, fnameindex); /* ignore results from 'lua_load' */
  636. return errfile(L, "read", fnameindex);
  637. }
  638. lua_remove(L, fnameindex);
  639. return status;
  640. }
  641. typedef struct LoadS {
  642. const char *s;
  643. size_t size;
  644. } LoadS;
  645. static const char *getS (lua_State *L, void *ud, size_t *size) {
  646. LoadS *ls = (LoadS *)ud;
  647. (void)L; /* not used */
  648. if (ls->size == 0) return NULL;
  649. *size = ls->size;
  650. ls->size = 0;
  651. return ls->s;
  652. }
  653. LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
  654. const char *name, const char *mode) {
  655. LoadS ls;
  656. ls.s = buff;
  657. ls.size = size;
  658. return lua_load(L, getS, &ls, name, mode);
  659. }
  660. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  661. return luaL_loadbuffer(L, s, strlen(s), s);
  662. }
  663. /* }====================================================== */
  664. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  665. if (!lua_getmetatable(L, obj)) /* no metatable? */
  666. return LUA_TNIL;
  667. else {
  668. int tt;
  669. lua_pushstring(L, event);
  670. tt = lua_rawget(L, -2);
  671. if (tt == LUA_TNIL) /* is metafield nil? */
  672. lua_pop(L, 2); /* remove metatable and metafield */
  673. else
  674. lua_remove(L, -2); /* remove only metatable */
  675. return tt; /* return metafield type */
  676. }
  677. }
  678. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  679. obj = lua_absindex(L, obj);
  680. if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */
  681. return 0;
  682. lua_pushvalue(L, obj);
  683. lua_call(L, 1, 1);
  684. return 1;
  685. }
  686. LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
  687. lua_Integer l;
  688. int isnum;
  689. lua_len(L, idx);
  690. l = lua_tointegerx(L, -1, &isnum);
  691. if (!isnum)
  692. luaL_error(L, "object length is not an integer");
  693. lua_pop(L, 1); /* remove object */
  694. return l;
  695. }
  696. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  697. if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
  698. if (!lua_isstring(L, -1))
  699. luaL_error(L, "'__tostring' must return a string");
  700. }
  701. else {
  702. switch (lua_type(L, idx)) {
  703. case LUA_TNUMBER: {
  704. if (lua_isinteger(L, idx))
  705. lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx));
  706. else
  707. lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx));
  708. break;
  709. }
  710. case LUA_TSTRING:
  711. lua_pushvalue(L, idx);
  712. break;
  713. case LUA_TBOOLEAN:
  714. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  715. break;
  716. case LUA_TNIL:
  717. lua_pushliteral(L, "nil");
  718. break;
  719. default: {
  720. int tt = luaL_getmetafield(L, idx, "__name"); /* try name */
  721. const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
  722. luaL_typename(L, idx);
  723. lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
  724. if (tt != LUA_TNIL)
  725. lua_remove(L, -2); /* remove '__name' */
  726. break;
  727. }
  728. }
  729. }
  730. return lua_tolstring(L, -1, len);
  731. }
  732. /*
  733. ** set functions from list 'l' into table at top - 'nup'; each
  734. ** function gets the 'nup' elements at the top as upvalues.
  735. ** Returns with only the table at the stack.
  736. */
  737. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  738. luaL_checkstack(L, nup, "too many upvalues");
  739. for (; l->name != NULL; l++) { /* fill the table with given functions */
  740. int i;
  741. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  742. lua_pushvalue(L, -nup);
  743. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  744. lua_setfield(L, -(nup + 2), l->name);
  745. }
  746. lua_pop(L, nup); /* remove upvalues */
  747. }
  748. /*
  749. ** ensure that stack[idx][fname] has a table and push that table
  750. ** into the stack
  751. */
  752. LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
  753. if (lua_getfield(L, idx, fname) == LUA_TTABLE)
  754. return 1; /* table already there */
  755. else {
  756. lua_pop(L, 1); /* remove previous result */
  757. idx = lua_absindex(L, idx);
  758. lua_newtable(L);
  759. lua_pushvalue(L, -1); /* copy to be left at top */
  760. lua_setfield(L, idx, fname); /* assign new table to field */
  761. return 0; /* false, because did not find table there */
  762. }
  763. }
  764. /*
  765. ** Stripped-down 'require': After checking "loaded" table, calls 'openf'
  766. ** to open a module, registers the result in 'package.loaded' table and,
  767. ** if 'glb' is true, also registers the result in the global table.
  768. ** Leaves resulting module on the top.
  769. */
  770. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  771. lua_CFunction openf, int glb) {
  772. luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  773. lua_getfield(L, -1, modname); /* LOADED[modname] */
  774. if (!lua_toboolean(L, -1)) { /* package not already loaded? */
  775. lua_pop(L, 1); /* remove field */
  776. lua_pushcfunction(L, openf);
  777. lua_pushstring(L, modname); /* argument to open function */
  778. lua_call(L, 1, 1); /* call 'openf' to open module */
  779. lua_pushvalue(L, -1); /* make copy of module (call result) */
  780. lua_setfield(L, -3, modname); /* LOADED[modname] = module */
  781. }
  782. lua_remove(L, -2); /* remove LOADED table */
  783. if (glb) {
  784. lua_pushvalue(L, -1); /* copy of module */
  785. lua_setglobal(L, modname); /* _G[modname] = module */
  786. }
  787. }
  788. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  789. const char *r) {
  790. const char *wild;
  791. size_t l = strlen(p);
  792. luaL_Buffer b;
  793. luaL_buffinit(L, &b);
  794. while ((wild = strstr(s, p)) != NULL) {
  795. luaL_addlstring(&b, s, wild - s); /* push prefix */
  796. luaL_addstring(&b, r); /* push replacement in place of pattern */
  797. s = wild + l; /* continue after 'p' */
  798. }
  799. luaL_addstring(&b, s); /* push last suffix */
  800. luaL_pushresult(&b);
  801. return lua_tostring(L, -1);
  802. }
  803. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  804. (void)ud; (void)osize; /* not used */
  805. if (nsize == 0) {
  806. free(ptr);
  807. return NULL;
  808. }
  809. else
  810. return realloc(ptr, nsize);
  811. }
  812. static int panic (lua_State *L) {
  813. lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  814. lua_tostring(L, -1));
  815. return 0; /* return to Lua to abort */
  816. }
  817. /*
  818. ** Emit a warning. '*previoustocont' signals whether previous message
  819. ** was to be continued by the current one.
  820. */
  821. static void warnf (void *ud, const char *message, int tocont) {
  822. int *previoustocont = (int *)ud;
  823. if (!*previoustocont) /* previous message was the last? */
  824. lua_writestringerror("%s", "Lua warning: "); /* start a new warning */
  825. lua_writestringerror("%s", message); /* write message */
  826. if (!tocont) /* is this the last part? */
  827. lua_writestringerror("%s", "\n"); /* finish message with end-of-line */
  828. *previoustocont = tocont;
  829. }
  830. LUALIB_API lua_State *luaL_newstate (void) {
  831. lua_State *L = lua_newstate(l_alloc, NULL);
  832. if (L) {
  833. int *previoustocont; /* space for warning state */
  834. lua_atpanic(L, &panic);
  835. previoustocont = (int *)lua_newuserdatauv(L, sizeof(int), 0);
  836. luaL_ref(L, LUA_REGISTRYINDEX); /* make sure it won't be collected */
  837. *previoustocont = 0; /* next message starts a new warning */
  838. lua_setwarnf(L, warnf, previoustocont);
  839. }
  840. return L;
  841. }
  842. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
  843. lua_Number v = lua_version(L);
  844. if (sz != LUAL_NUMSIZES) /* check numeric types */
  845. luaL_error(L, "core and library have incompatible numeric types");
  846. else if (v != ver)
  847. luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
  848. (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v);
  849. }