lauxlib.c 29 KB

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