lauxlib.c 27 KB

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