lauxlib.c 32 KB

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