lauxlib.c 32 KB

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