2
0

lauxlib.c 28 KB

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