lauxlib.c 27 KB

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