lauxlib.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. /*
  2. ** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $
  3. ** Auxiliary functions for building Lua libraries
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <errno.h>
  8. #include <stdarg.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. /* This file uses only the official API of Lua.
  13. ** Any function declared here could be written as an application function.
  14. */
  15. #define lauxlib_c
  16. #define LUA_LIB
  17. #include "lua.h"
  18. #include "lrotable.h"
  19. #include "lauxlib.h"
  20. #include "lgc.h"
  21. #include "ldo.h"
  22. #include "lobject.h"
  23. #include "lstate.h"
  24. #include "legc.h"
  25. #define FREELIST_REF 0 /* free list of references */
  26. /* convert a stack index to positive */
  27. #define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
  28. lua_gettop(L) + (i) + 1)
  29. // Parameters for luaI_openlib
  30. #define LUA_USECCLOSURES 0
  31. #define LUA_USELIGHTFUNCTIONS 1
  32. /*
  33. ** {======================================================
  34. ** Error-report functions
  35. ** =======================================================
  36. */
  37. LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
  38. lua_Debug ar;
  39. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  40. return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
  41. lua_getinfo(L, "n", &ar);
  42. if (strcmp(ar.namewhat, "method") == 0) {
  43. narg--; /* do not count `self' */
  44. if (narg == 0) /* error is in the self argument itself? */
  45. return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
  46. ar.name, extramsg);
  47. }
  48. if (ar.name == NULL)
  49. ar.name = "?";
  50. return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
  51. narg, ar.name, extramsg);
  52. }
  53. LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
  54. const char *msg = lua_pushfstring(L, "%s expected, got %s",
  55. tname, luaL_typename(L, narg));
  56. return luaL_argerror(L, narg, msg);
  57. }
  58. static void tag_error (lua_State *L, int narg, int tag) {
  59. luaL_typerror(L, narg, lua_typename(L, tag));
  60. }
  61. LUALIB_API void luaL_where (lua_State *L, int level) {
  62. lua_Debug ar;
  63. if (lua_getstack(L, level, &ar)) { /* check function at level */
  64. lua_getinfo(L, "Sl", &ar); /* get info about it */
  65. if (ar.currentline > 0) { /* is there info? */
  66. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  67. return;
  68. }
  69. }
  70. lua_pushliteral(L, ""); /* else, no information available... */
  71. }
  72. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  73. va_list argp;
  74. va_start(argp, fmt);
  75. luaL_where(L, 1);
  76. lua_pushvfstring(L, fmt, argp);
  77. va_end(argp);
  78. lua_concat(L, 2);
  79. return lua_error(L);
  80. }
  81. /* }====================================================== */
  82. LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
  83. const char *const lst[]) {
  84. const char *name = (def) ? luaL_optstring(L, narg, def) :
  85. luaL_checkstring(L, narg);
  86. int i;
  87. for (i=0; lst[i]; i++)
  88. if (strcmp(lst[i], name) == 0)
  89. return i;
  90. return luaL_argerror(L, narg,
  91. lua_pushfstring(L, "invalid option " LUA_QS, name));
  92. }
  93. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  94. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
  95. if (!lua_isnil(L, -1)) /* name already in use? */
  96. return 0; /* leave previous value on top, but return 0 */
  97. lua_pop(L, 1);
  98. lua_newtable(L); /* create metatable */
  99. lua_pushvalue(L, -1);
  100. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  101. return 1;
  102. }
  103. LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, void *p) {
  104. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
  105. if (!lua_isnil(L, -1)) /* name already in use? */
  106. return 0; /* leave previous value on top, but return 0 */
  107. lua_pop(L, 1);
  108. lua_pushrotable(L, p);
  109. lua_pushvalue(L, -1);
  110. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  111. return 1;
  112. }
  113. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  114. void *p = lua_touserdata(L, ud);
  115. if (p != NULL) { /* value is a userdata? */
  116. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  117. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
  118. if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */
  119. lua_pop(L, 2); /* remove both metatables */
  120. return p;
  121. }
  122. }
  123. }
  124. luaL_typerror(L, ud, tname); /* else error */
  125. return NULL; /* to avoid warnings */
  126. }
  127. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
  128. if (!lua_checkstack(L, space))
  129. luaL_error(L, "stack overflow (%s)", mes);
  130. }
  131. LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
  132. if (lua_type(L, narg) != t)
  133. tag_error(L, narg, t);
  134. }
  135. LUALIB_API void luaL_checkanyfunction (lua_State *L, int narg) {
  136. if (lua_type(L, narg) != LUA_TFUNCTION && lua_type(L, narg) != LUA_TLIGHTFUNCTION) {
  137. const char *msg = lua_pushfstring(L, "function or lightfunction expected, got %s",
  138. luaL_typename(L, narg));
  139. luaL_argerror(L, narg, msg);
  140. }
  141. }
  142. LUALIB_API void luaL_checkanytable (lua_State *L, int narg) {
  143. if (lua_type(L, narg) != LUA_TTABLE && lua_type(L, narg) != LUA_TROTABLE) {
  144. const char *msg = lua_pushfstring(L, "table or rotable expected, got %s",
  145. luaL_typename(L, narg));
  146. luaL_argerror(L, narg, msg);
  147. }
  148. }
  149. LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  150. if (lua_type(L, narg) == LUA_TNONE)
  151. luaL_argerror(L, narg, "value expected");
  152. }
  153. LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
  154. const char *s = lua_tolstring(L, narg, len);
  155. if (!s) tag_error(L, narg, LUA_TSTRING);
  156. return s;
  157. }
  158. LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
  159. const char *def, size_t *len) {
  160. if (lua_isnoneornil(L, narg)) {
  161. if (len)
  162. *len = (def ? strlen(def) : 0);
  163. return def;
  164. }
  165. else return luaL_checklstring(L, narg, len);
  166. }
  167. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
  168. lua_Number d = lua_tonumber(L, narg);
  169. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  170. tag_error(L, narg, LUA_TNUMBER);
  171. return d;
  172. }
  173. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  174. return luaL_opt(L, luaL_checknumber, narg, def);
  175. }
  176. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  177. lua_Integer d = lua_tointeger(L, narg);
  178. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  179. tag_error(L, narg, LUA_TNUMBER);
  180. return d;
  181. }
  182. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  183. lua_Integer def) {
  184. return luaL_opt(L, luaL_checkinteger, narg, def);
  185. }
  186. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  187. if (!lua_getmetatable(L, obj)) /* no metatable? */
  188. return 0;
  189. lua_pushstring(L, event);
  190. lua_rawget(L, -2);
  191. if (lua_isnil(L, -1)) {
  192. lua_pop(L, 2); /* remove metatable and metafield */
  193. return 0;
  194. }
  195. else {
  196. lua_remove(L, -2); /* remove only metatable */
  197. return 1;
  198. }
  199. }
  200. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  201. obj = abs_index(L, obj);
  202. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  203. return 0;
  204. lua_pushvalue(L, obj);
  205. lua_call(L, 1, 1);
  206. return 1;
  207. }
  208. LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
  209. const luaL_Reg *l) {
  210. luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
  211. }
  212. LUALIB_API void (luaL_register_light) (lua_State *L, const char *libname,
  213. const luaL_Reg *l) {
  214. #if LUA_OPTIMIZE_MEMORY > 0
  215. luaI_openlib(L, libname, l, 0, LUA_USELIGHTFUNCTIONS);
  216. #else
  217. luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
  218. #endif
  219. }
  220. static int libsize (const luaL_Reg *l) {
  221. int size = 0;
  222. for (; l->name; l++) size++;
  223. return size;
  224. }
  225. LUALIB_API void luaI_openlib (lua_State *L, const char *libname,
  226. const luaL_Reg *l, int nup, int ftype) {
  227. if (libname) {
  228. int size = libsize(l);
  229. /* check whether lib already exists */
  230. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
  231. lua_getfield(L, -1, libname); /* get _LOADED[libname] */
  232. if (!lua_istable(L, -1)) { /* not found? */
  233. lua_pop(L, 1); /* remove previous result */
  234. /* try global variable (and create one if it does not exist) */
  235. if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
  236. luaL_error(L, "name conflict for module " LUA_QS, libname);
  237. lua_pushvalue(L, -1);
  238. lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
  239. }
  240. lua_remove(L, -2); /* remove _LOADED table */
  241. lua_insert(L, -(nup+1)); /* move library table to below upvalues */
  242. }
  243. for (; l->name; l++) {
  244. int i;
  245. for (i=0; i<nup; i++) /* copy upvalues to the top */
  246. lua_pushvalue(L, -nup);
  247. if (ftype == LUA_USELIGHTFUNCTIONS)
  248. lua_pushlightfunction(L, l->func);
  249. else
  250. lua_pushcclosure(L, l->func, nup);
  251. lua_setfield(L, -(nup+2), l->name);
  252. }
  253. lua_pop(L, nup); /* remove upvalues */
  254. }
  255. /*
  256. ** {======================================================
  257. ** getn-setn: size for arrays
  258. ** =======================================================
  259. */
  260. #if defined(LUA_COMPAT_GETN)
  261. static int checkint (lua_State *L, int topop) {
  262. int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
  263. lua_pop(L, topop);
  264. return n;
  265. }
  266. static void getsizes (lua_State *L) {
  267. lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");
  268. if (lua_isnil(L, -1)) { /* no `size' table? */
  269. lua_pop(L, 1); /* remove nil */
  270. lua_newtable(L); /* create it */
  271. lua_pushvalue(L, -1); /* `size' will be its own metatable */
  272. lua_setmetatable(L, -2);
  273. lua_pushliteral(L, "kv");
  274. lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */
  275. lua_pushvalue(L, -1);
  276. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */
  277. }
  278. }
  279. LUALIB_API void luaL_setn (lua_State *L, int t, int n) {
  280. t = abs_index(L, t);
  281. lua_pushliteral(L, "n");
  282. lua_rawget(L, t);
  283. if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */
  284. lua_pushliteral(L, "n"); /* use it */
  285. lua_pushinteger(L, n);
  286. lua_rawset(L, t);
  287. }
  288. else { /* use `sizes' */
  289. getsizes(L);
  290. lua_pushvalue(L, t);
  291. lua_pushinteger(L, n);
  292. lua_rawset(L, -3); /* sizes[t] = n */
  293. lua_pop(L, 1); /* remove `sizes' */
  294. }
  295. }
  296. LUALIB_API int luaL_getn (lua_State *L, int t) {
  297. int n;
  298. t = abs_index(L, t);
  299. lua_pushliteral(L, "n"); /* try t.n */
  300. lua_rawget(L, t);
  301. if ((n = checkint(L, 1)) >= 0) return n;
  302. getsizes(L); /* else try sizes[t] */
  303. lua_pushvalue(L, t);
  304. lua_rawget(L, -2);
  305. if ((n = checkint(L, 2)) >= 0) return n;
  306. return (int)lua_objlen(L, t);
  307. }
  308. #endif
  309. /* }====================================================== */
  310. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  311. const char *r) {
  312. const char *wild;
  313. size_t l = strlen(p);
  314. luaL_Buffer b;
  315. luaL_buffinit(L, &b);
  316. while ((wild = strstr(s, p)) != NULL) {
  317. luaL_addlstring(&b, s, wild - s); /* push prefix */
  318. luaL_addstring(&b, r); /* push replacement in place of pattern */
  319. s = wild + l; /* continue after `p' */
  320. }
  321. luaL_addstring(&b, s); /* push last suffix */
  322. luaL_pushresult(&b);
  323. return lua_tostring(L, -1);
  324. }
  325. LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
  326. const char *fname, int szhint) {
  327. const char *e;
  328. lua_pushvalue(L, idx);
  329. do {
  330. e = strchr(fname, '.');
  331. if (e == NULL) e = fname + strlen(fname);
  332. lua_pushlstring(L, fname, e - fname);
  333. lua_rawget(L, -2);
  334. if (lua_isnil(L, -1)) {
  335. /* If looking for a global variable, check the rotables too */
  336. void *ptable = luaR_findglobal(fname, e - fname);
  337. if (ptable) {
  338. lua_pop(L, 1);
  339. lua_pushrotable(L, ptable);
  340. }
  341. }
  342. if (lua_isnil(L, -1)) { /* no such field? */
  343. lua_pop(L, 1); /* remove this nil */
  344. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  345. lua_pushlstring(L, fname, e - fname);
  346. lua_pushvalue(L, -2);
  347. lua_settable(L, -4); /* set new table into field */
  348. }
  349. else if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) { /* field has a non-table value? */
  350. lua_pop(L, 2); /* remove table and value */
  351. return fname; /* return problematic part of the name */
  352. }
  353. lua_remove(L, -2); /* remove previous table */
  354. fname = e + 1;
  355. } while (*e == '.');
  356. return NULL;
  357. }
  358. /*
  359. ** {======================================================
  360. ** Generic Buffer manipulation
  361. ** =======================================================
  362. */
  363. #define bufflen(B) ((B)->p - (B)->buffer)
  364. #define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
  365. #define LIMIT (LUA_MINSTACK/2)
  366. static int emptybuffer (luaL_Buffer *B) {
  367. size_t l = bufflen(B);
  368. if (l == 0) return 0; /* put nothing on stack */
  369. else {
  370. lua_pushlstring(B->L, B->buffer, l);
  371. B->p = B->buffer;
  372. B->lvl++;
  373. return 1;
  374. }
  375. }
  376. static void adjuststack (luaL_Buffer *B) {
  377. if (B->lvl > 1) {
  378. lua_State *L = B->L;
  379. int toget = 1; /* number of levels to concat */
  380. size_t toplen = lua_strlen(L, -1);
  381. do {
  382. size_t l = lua_strlen(L, -(toget+1));
  383. if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
  384. toplen += l;
  385. toget++;
  386. }
  387. else break;
  388. } while (toget < B->lvl);
  389. lua_concat(L, toget);
  390. B->lvl = B->lvl - toget + 1;
  391. }
  392. }
  393. LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
  394. if (emptybuffer(B))
  395. adjuststack(B);
  396. return B->buffer;
  397. }
  398. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  399. while (l--)
  400. luaL_addchar(B, *s++);
  401. }
  402. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  403. luaL_addlstring(B, s, strlen(s));
  404. }
  405. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  406. emptybuffer(B);
  407. lua_concat(B->L, B->lvl);
  408. B->lvl = 1;
  409. }
  410. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  411. lua_State *L = B->L;
  412. size_t vl;
  413. const char *s = lua_tolstring(L, -1, &vl);
  414. if (vl <= bufffree(B)) { /* fit into buffer? */
  415. memcpy(B->p, s, vl); /* put it there */
  416. B->p += vl;
  417. lua_pop(L, 1); /* remove from stack */
  418. }
  419. else {
  420. if (emptybuffer(B))
  421. lua_insert(L, -2); /* put buffer before new value */
  422. B->lvl++; /* add new value into B stack */
  423. adjuststack(B);
  424. }
  425. }
  426. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  427. B->L = L;
  428. B->p = B->buffer;
  429. B->lvl = 0;
  430. }
  431. /* }====================================================== */
  432. LUALIB_API int luaL_ref (lua_State *L, int t) {
  433. int ref;
  434. t = abs_index(L, t);
  435. if (lua_isnil(L, -1)) {
  436. lua_pop(L, 1); /* remove from stack */
  437. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  438. }
  439. lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
  440. ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
  441. lua_pop(L, 1); /* remove it from stack */
  442. if (ref != 0) { /* any free element? */
  443. lua_rawgeti(L, t, ref); /* remove it from list */
  444. lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
  445. }
  446. else { /* no free elements */
  447. ref = (int)lua_objlen(L, t);
  448. ref++; /* create new reference */
  449. }
  450. lua_rawseti(L, t, ref);
  451. return ref;
  452. }
  453. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  454. if (ref >= 0) {
  455. t = abs_index(L, t);
  456. lua_rawgeti(L, t, FREELIST_REF);
  457. lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
  458. lua_pushinteger(L, ref);
  459. lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
  460. }
  461. }
  462. /*
  463. ** {======================================================
  464. ** Load functions
  465. ** =======================================================
  466. */
  467. typedef struct LoadF {
  468. int extraline;
  469. FILE *f;
  470. char buff[LUAL_BUFFERSIZE];
  471. } LoadF;
  472. static const char *getF (lua_State *L, void *ud, size_t *size) {
  473. LoadF *lf = (LoadF *)ud;
  474. (void)L;
  475. if (lf->extraline) {
  476. lf->extraline = 0;
  477. *size = 1;
  478. return "\n";
  479. }
  480. if (feof(lf->f)) return NULL;
  481. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);
  482. return (*size > 0) ? lf->buff : NULL;
  483. }
  484. static int errfile (lua_State *L, const char *what, int fnameindex) {
  485. const char *serr = strerror(errno);
  486. const char *filename = lua_tostring(L, fnameindex) + 1;
  487. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  488. lua_remove(L, fnameindex);
  489. return LUA_ERRFILE;
  490. }
  491. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  492. LoadF lf;
  493. int status, readstatus;
  494. int c;
  495. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  496. lf.extraline = 0;
  497. if (filename == NULL) {
  498. lua_pushliteral(L, "=stdin");
  499. lf.f = stdin;
  500. }
  501. else {
  502. lua_pushfstring(L, "@%s", filename);
  503. lf.f = fopen(filename, "r");
  504. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  505. }
  506. c = getc(lf.f);
  507. if (c == '#') { /* Unix exec. file? */
  508. lf.extraline = 1;
  509. while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
  510. if (c == '\n') c = getc(lf.f);
  511. }
  512. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  513. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  514. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  515. /* skip eventual `#!...' */
  516. while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
  517. lf.extraline = 0;
  518. }
  519. ungetc(c, lf.f);
  520. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  521. readstatus = ferror(lf.f);
  522. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  523. if (readstatus) {
  524. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  525. return errfile(L, "read", fnameindex);
  526. }
  527. lua_remove(L, fnameindex);
  528. return status;
  529. }
  530. typedef struct LoadS {
  531. const char *s;
  532. size_t size;
  533. } LoadS;
  534. static const char *getS (lua_State *L, void *ud, size_t *size) {
  535. LoadS *ls = (LoadS *)ud;
  536. (void)L;
  537. if (L == NULL && size == NULL) // direct mode check
  538. return NULL;
  539. if (ls->size == 0) return NULL;
  540. *size = ls->size;
  541. ls->size = 0;
  542. return ls->s;
  543. }
  544. LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
  545. const char *name) {
  546. LoadS ls;
  547. ls.s = buff;
  548. ls.size = size;
  549. return lua_load(L, getS, &ls, name);
  550. }
  551. LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) {
  552. return luaL_loadbuffer(L, s, strlen(s), s);
  553. }
  554. /* }====================================================== */
  555. static int l_check_memlimit(lua_State *L, size_t needbytes) {
  556. global_State *g = G(L);
  557. int cycle_count = 0;
  558. lu_mem limit = g->memlimit - needbytes;
  559. /* make sure the GC is not disabled. */
  560. if (!is_block_gc(L)) {
  561. while (g->totalbytes >= limit) {
  562. /* only allow the GC to finished atleast 1 full cycle. */
  563. if (g->gcstate == GCSpause && ++cycle_count > 1) break;
  564. luaC_step(L);
  565. }
  566. }
  567. return (g->totalbytes >= limit) ? 1 : 0;
  568. }
  569. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  570. lua_State *L = (lua_State *)ud;
  571. int mode = L == NULL ? 0 : G(L)->egcmode;
  572. void *nptr;
  573. if (nsize == 0) {
  574. free(ptr);
  575. return NULL;
  576. }
  577. if (L != NULL && (mode & EGC_ALWAYS)) /* always collect memory if requested */
  578. luaC_fullgc(L);
  579. if(nsize > osize && L != NULL) {
  580. #if defined(LUA_STRESS_EMERGENCY_GC)
  581. luaC_fullgc(L);
  582. #endif
  583. if(G(L)->memlimit > 0 && (mode & EGC_ON_MEM_LIMIT) && l_check_memlimit(L, nsize - osize))
  584. return NULL;
  585. }
  586. nptr = realloc(ptr, nsize);
  587. if (nptr == NULL && L != NULL && (mode & EGC_ON_ALLOC_FAILURE)) {
  588. luaC_fullgc(L); /* emergency full collection. */
  589. nptr = realloc(ptr, nsize); /* try allocation again */
  590. }
  591. return nptr;
  592. }
  593. static int panic (lua_State *L) {
  594. (void)L; /* to avoid warnings */
  595. #if defined(LUA_USE_STDIO)
  596. fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
  597. lua_tostring(L, -1));
  598. #else
  599. luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  600. lua_tostring(L, -1));
  601. #endif
  602. return 0;
  603. }
  604. LUALIB_API lua_State *luaL_newstate (void) {
  605. lua_State *L = lua_newstate(l_alloc, NULL);
  606. lua_setallocf(L, l_alloc, L); /* allocator need lua_State. */
  607. if (L) lua_atpanic(L, &panic);
  608. return L;
  609. }