2 ** $Id: lbaselib.c,v 1.130c 2003/04/03 13:35:34 roberto Exp $
4 ** See Copyright Notice in lua.h
25 ** If your system does not support `stdout', you can just remove this function.
26 ** If you need, you can define your own `print' function, following this
27 ** model but changing `fputs' to put the strings at a proper place
28 ** (a console window or a log file, for instance).
30 static int luaB_print (lua_State
*L
) {
31 int n
= lua_gettop(L
); /* number of arguments */
33 lua_getglobal(L
, "tostring");
34 for (i
=1; i
<=n
; i
++) {
36 lua_pushvalue(L
, -1); /* function to be called */
37 lua_pushvalue(L
, i
); /* value to print */
39 s
= lua_tostring(L
, -1); /* get result */
41 return luaL_error(L
, "`tostring' must return a string to `print'");
42 if (i
>1) fputs("\t", stdout
);
44 lua_pop(L
, 1); /* pop result */
51 static int luaB_tonumber (lua_State
*L
) {
52 int base
= luaL_optint(L
, 2, 10);
53 if (base
== 10) { /* standard conversion */
55 if (lua_isnumber(L
, 1)) {
56 lua_pushnumber(L
, lua_tonumber(L
, 1));
61 const char *s1
= luaL_checkstring(L
, 1);
64 luaL_argcheck(L
, 2 <= base
&& base
<= 36, 2, "base out of range");
65 n
= strtoul(s1
, &s2
, base
);
66 if (s1
!= s2
) { /* at least one valid digit? */
67 while (isspace((unsigned char)(*s2
))) s2
++; /* skip trailing spaces */
68 if (*s2
== '\0') { /* no invalid trailing characters? */
69 lua_pushnumber(L
, (lua_Number
)n
);
74 lua_pushnil(L
); /* else not a number */
79 static int luaB_error (lua_State
*L
) {
80 int level
= luaL_optint(L
, 2, 1);
82 if (!lua_isstring(L
, 1) || level
== 0)
83 lua_pushvalue(L
, 1); /* propagate error message without changes */
84 else { /* add extra information */
93 static int luaB_getmetatable (lua_State
*L
) {
95 if (!lua_getmetatable(L
, 1)) {
97 return 1; /* no metatable */
99 luaL_getmetafield(L
, 1, "__metatable");
100 return 1; /* returns either __metatable field (if present) or metatable */
104 static int luaB_setmetatable (lua_State
*L
) {
105 int t
= lua_type(L
, 2);
106 luaL_checktype(L
, 1, LUA_TTABLE
);
107 luaL_argcheck(L
, t
== LUA_TNIL
|| t
== LUA_TTABLE
, 2,
108 "nil or table expected");
109 if (luaL_getmetafield(L
, 1, "__metatable"))
110 luaL_error(L
, "cannot change a protected metatable");
112 lua_setmetatable(L
, 1);
117 static void getfunc (lua_State
*L
) {
118 if (lua_isfunction(L
, 1)) lua_pushvalue(L
, 1);
121 int level
= luaL_optint(L
, 1, 1);
122 luaL_argcheck(L
, level
>= 0, 1, "level must be non-negative");
123 if (lua_getstack(L
, level
, &ar
) == 0)
124 luaL_argerror(L
, 1, "invalid level");
125 lua_getinfo(L
, "f", &ar
);
126 if (lua_isnil(L
, -1))
127 luaL_error(L
, "no function environment for tail call at level %d",
133 static int aux_getfenv (lua_State
*L
) {
135 lua_pushliteral(L
, "__fenv");
137 return !lua_isnil(L
, -1);
141 static int luaB_getfenv (lua_State
*L
) {
143 if (!aux_getfenv(L
)) /* __fenv not defined? */
144 lua_pop(L
, 1); /* remove it, to return real environment */
149 static int luaB_setfenv (lua_State
*L
) {
150 luaL_checktype(L
, 2, LUA_TTABLE
);
152 if (aux_getfenv(L
)) /* __fenv defined? */
153 luaL_error(L
, "`setfenv' cannot change a protected environment");
155 lua_pop(L
, 2); /* remove __fenv and real environment table */
157 if (lua_isnumber(L
, 1) && lua_tonumber(L
, 1) == 0)
158 lua_replace(L
, LUA_GLOBALSINDEX
);
159 else if (lua_setfenv(L
, -2) == 0)
160 luaL_error(L
, "`setfenv' cannot change environment of given function");
165 static int luaB_rawequal (lua_State
*L
) {
168 lua_pushboolean(L
, lua_rawequal(L
, 1, 2));
173 static int luaB_rawget (lua_State
*L
) {
174 luaL_checktype(L
, 1, LUA_TTABLE
);
181 static int luaB_rawset (lua_State
*L
) {
182 luaL_checktype(L
, 1, LUA_TTABLE
);
191 static int luaB_gcinfo (lua_State
*L
) {
192 lua_pushnumber(L
, (lua_Number
)lua_getgccount(L
));
193 lua_pushnumber(L
, (lua_Number
)lua_getgcthreshold(L
));
198 static int luaB_collectgarbage (lua_State
*L
) {
199 lua_setgcthreshold(L
, luaL_optint(L
, 1, 0));
204 static int luaB_type (lua_State
*L
) {
206 lua_pushstring(L
, lua_typename(L
, lua_type(L
, 1)));
211 static int luaB_next (lua_State
*L
) {
212 luaL_checktype(L
, 1, LUA_TTABLE
);
213 lua_settop(L
, 2); /* create a 2nd argument if there isn't one */
223 static int luaB_pairs (lua_State
*L
) {
224 luaL_checktype(L
, 1, LUA_TTABLE
);
225 lua_pushliteral(L
, "next");
226 lua_rawget(L
, LUA_GLOBALSINDEX
); /* return generator, */
227 lua_pushvalue(L
, 1); /* state, */
228 lua_pushnil(L
); /* and initial value */
233 static int luaB_ipairs (lua_State
*L
) {
234 lua_Number i
= lua_tonumber(L
, 2);
235 luaL_checktype(L
, 1, LUA_TTABLE
);
236 if (i
== 0 && lua_isnone(L
, 2)) { /* `for' start? */
237 lua_pushliteral(L
, "ipairs");
238 lua_rawget(L
, LUA_GLOBALSINDEX
); /* return generator, */
239 lua_pushvalue(L
, 1); /* state, */
240 lua_pushnumber(L
, 0); /* and initial value */
243 else { /* `for' step */
244 i
++; /* next value */
245 lua_pushnumber(L
, i
);
246 lua_rawgeti(L
, 1, (int)i
);
247 return (lua_isnil(L
, -1)) ? 0 : 2;
252 static int load_aux (lua_State
*L
, int status
) {
253 if (status
== 0) /* OK? */
257 lua_insert(L
, -2); /* put before error message */
258 return 2; /* return nil plus error message */
263 static int luaB_loadstring (lua_State
*L
) {
265 const char *s
= luaL_checklstring(L
, 1, &l
);
266 const char *chunkname
= luaL_optstring(L
, 2, s
);
267 return load_aux(L
, luaL_loadbuffer(L
, s
, l
, chunkname
));
271 static int luaB_loadfile (lua_State
*L
) {
272 const char *fname
= luaL_optstring(L
, 1, NULL
);
273 return load_aux(L
, luaL_loadfile(L
, fname
));
277 static int luaB_dofile (lua_State
*L
) {
278 const char *fname
= luaL_optstring(L
, 1, NULL
);
279 int n
= lua_gettop(L
);
280 int status
= luaL_loadfile(L
, fname
);
281 if (status
!= 0) lua_error(L
);
282 lua_call(L
, 0, LUA_MULTRET
);
283 return lua_gettop(L
) - n
;
287 static int luaB_assert (lua_State
*L
) {
289 if (!lua_toboolean(L
, 1))
290 return luaL_error(L
, "%s", luaL_optstring(L
, 2, "assertion failed!"));
296 static int luaB_unpack (lua_State
*L
) {
298 luaL_checktype(L
, 1, LUA_TTABLE
);
300 luaL_checkstack(L
, n
, "table too big to unpack");
301 for (i
=1; i
<=n
; i
++) /* push arg[1...n] */
302 lua_rawgeti(L
, 1, i
);
307 static int luaB_pcall (lua_State
*L
) {
310 status
= lua_pcall(L
, lua_gettop(L
) - 1, LUA_MULTRET
, 0);
311 lua_pushboolean(L
, (status
== 0));
313 return lua_gettop(L
); /* return status + all results */
317 static int luaB_xpcall (lua_State
*L
) {
321 lua_insert(L
, 1); /* put error function under function to be called */
322 status
= lua_pcall(L
, 0, LUA_MULTRET
, 1);
323 lua_pushboolean(L
, (status
== 0));
325 return lua_gettop(L
); /* return status + all results */
329 static int luaB_tostring (lua_State
*L
) {
332 if (luaL_callmeta(L
, 1, "__tostring")) /* is there a metafield? */
333 return 1; /* use its value */
334 switch (lua_type(L
, 1)) {
336 lua_pushstring(L
, lua_tostring(L
, 1));
342 lua_pushstring(L
, (lua_toboolean(L
, 1) ? "true" : "false"));
345 sprintf(buff
, "table: %p", lua_topointer(L
, 1));
348 sprintf(buff
, "function: %p", lua_topointer(L
, 1));
351 case LUA_TLIGHTUSERDATA
:
352 sprintf(buff
, "userdata: %p", lua_touserdata(L
, 1));
355 sprintf(buff
, "thread: %p", (void *)lua_tothread(L
, 1));
358 lua_pushliteral(L
, "nil");
361 lua_pushstring(L
, buff
);
366 static int luaB_newproxy (lua_State
*L
) {
368 lua_newuserdata(L
, 0); /* create proxy */
369 if (lua_toboolean(L
, 1) == 0)
370 return 1; /* no metatable */
371 else if (lua_isboolean(L
, 1)) {
372 lua_newtable(L
); /* create a new metatable `m' ... */
373 lua_pushvalue(L
, -1); /* ... and mark `m' as a valid metatable */
374 lua_pushboolean(L
, 1);
375 lua_rawset(L
, lua_upvalueindex(1)); /* weaktable[m] = true */
378 int validproxy
= 0; /* to check if weaktable[metatable(u)] == true */
379 if (lua_getmetatable(L
, 1)) {
380 lua_rawget(L
, lua_upvalueindex(1));
381 validproxy
= lua_toboolean(L
, -1);
382 lua_pop(L
, 1); /* remove value */
384 luaL_argcheck(L
, validproxy
, 1, "boolean or proxy expected");
385 lua_getmetatable(L
, 1); /* metatable is valid; get it */
387 lua_setmetatable(L
, 2);
393 ** {======================================================
394 ** `require' function
395 ** =======================================================
399 /* name of global that holds table with loaded packages */
400 #define REQTAB "_LOADED"
402 /* name of global that holds the search path for packages */
403 #define LUA_PATH "LUA_PATH"
406 #define LUA_PATH_SEP ';'
409 #ifndef LUA_PATH_MARK
410 #define LUA_PATH_MARK '?'
413 #ifndef LUA_PATH_DEFAULT
414 #define LUA_PATH_DEFAULT "?;?.lua"
418 static const char *getpath (lua_State
*L
) {
420 lua_getglobal(L
, LUA_PATH
); /* try global variable */
421 path
= lua_tostring(L
, -1);
423 if (path
) return path
;
424 path
= getenv(LUA_PATH
); /* else try environment variable */
425 if (path
) return path
;
426 return LUA_PATH_DEFAULT
; /* else use default */
430 static const char *pushnextpath (lua_State
*L
, const char *path
) {
432 if (*path
== '\0') return NULL
; /* no more paths */
433 if (*path
== LUA_PATH_SEP
) path
++; /* skip separator */
434 l
= strchr(path
, LUA_PATH_SEP
); /* find next separator */
435 if (l
== NULL
) l
= path
+strlen(path
);
436 lua_pushlstring(L
, path
, l
- path
); /* directory name */
441 static void pushcomposename (lua_State
*L
) {
442 const char *path
= lua_tostring(L
, -1);
445 while ((wild
= strchr(path
, LUA_PATH_MARK
)) != NULL
) {
446 /* is there stack space for prefix, name, and eventual last sufix? */
447 luaL_checkstack(L
, 3, "too many marks in a path component");
448 lua_pushlstring(L
, path
, wild
- path
); /* push prefix */
449 lua_pushvalue(L
, 1); /* push package name (in place of MARK) */
450 path
= wild
+ 1; /* continue after MARK */
453 lua_pushstring(L
, path
); /* push last sufix (`n' already includes this) */
458 static int luaB_require (lua_State
*L
) {
460 int status
= LUA_ERRFILE
; /* not found (yet) */
461 luaL_checkstring(L
, 1);
463 lua_getglobal(L
, REQTAB
);
464 if (!lua_istable(L
, 2)) return luaL_error(L
, "`" REQTAB
"' is not a table");
466 lua_pushvalue(L
, 1); /* check package's name in book-keeping table */
468 if (lua_toboolean(L
, -1)) /* is it there? */
469 return 1; /* package is already loaded; return its result */
470 else { /* must load it */
471 while (status
== LUA_ERRFILE
) {
472 lua_settop(L
, 3); /* reset stack position */
473 if ((path
= pushnextpath(L
, path
)) == NULL
) break;
475 status
= luaL_loadfile(L
, lua_tostring(L
, -1)); /* try to load it */
480 lua_getglobal(L
, "_REQUIREDNAME"); /* save previous name */
481 lua_insert(L
, -2); /* put it below function */
483 lua_setglobal(L
, "_REQUIREDNAME"); /* set new name */
484 lua_call(L
, 0, 1); /* run loaded module */
485 lua_insert(L
, -2); /* put result below previous name */
486 lua_setglobal(L
, "_REQUIREDNAME"); /* reset to previous name */
487 if (lua_isnil(L
, -1)) { /* no/nil return? */
488 lua_pushboolean(L
, 1);
489 lua_replace(L
, -2); /* replace to true */
492 lua_pushvalue(L
, -2);
493 lua_rawset(L
, 2); /* mark it as loaded */
494 return 1; /* return value */
496 case LUA_ERRFILE
: { /* file not found */
497 return luaL_error(L
, "could not load package `%s' from path `%s'",
498 lua_tostring(L
, 1), getpath(L
));
501 return luaL_error(L
, "error loading package `%s' (%s)",
502 lua_tostring(L
, 1), lua_tostring(L
, -1));
507 /* }====================================================== */
510 static const luaL_reg base_funcs
[] = {
511 {"error", luaB_error
},
512 {"getmetatable", luaB_getmetatable
},
513 {"setmetatable", luaB_setmetatable
},
514 {"getfenv", luaB_getfenv
},
515 {"setfenv", luaB_setfenv
},
517 {"ipairs", luaB_ipairs
},
518 {"pairs", luaB_pairs
},
519 {"print", luaB_print
},
520 {"tonumber", luaB_tonumber
},
521 {"tostring", luaB_tostring
},
523 {"assert", luaB_assert
},
524 {"unpack", luaB_unpack
},
525 {"rawequal", luaB_rawequal
},
526 {"rawget", luaB_rawget
},
527 {"rawset", luaB_rawset
},
528 {"pcall", luaB_pcall
},
529 {"xpcall", luaB_xpcall
},
530 {"collectgarbage", luaB_collectgarbage
},
531 {"gcinfo", luaB_gcinfo
},
532 {"loadfile", luaB_loadfile
},
533 {"dofile", luaB_dofile
},
534 {"loadstring", luaB_loadstring
},
535 {"require", luaB_require
},
541 ** {======================================================
543 ** =======================================================
546 static int auxresume (lua_State
*L
, lua_State
*co
, int narg
) {
548 if (!lua_checkstack(co
, narg
))
549 luaL_error(L
, "too many arguments to resume");
550 lua_xmove(L
, co
, narg
);
551 status
= lua_resume(co
, narg
);
553 int nres
= lua_gettop(co
);
554 if (!lua_checkstack(L
, nres
))
555 luaL_error(L
, "too many results to resume");
556 lua_xmove(co
, L
, nres
); /* move yielded values */
560 lua_xmove(co
, L
, 1); /* move error message */
561 return -1; /* error flag */
566 static int luaB_coresume (lua_State
*L
) {
567 lua_State
*co
= lua_tothread(L
, 1);
569 luaL_argcheck(L
, co
, 1, "coroutine expected");
570 r
= auxresume(L
, co
, lua_gettop(L
) - 1);
572 lua_pushboolean(L
, 0);
574 return 2; /* return false + error message */
577 lua_pushboolean(L
, 1);
578 lua_insert(L
, -(r
+ 1));
579 return r
+ 1; /* return true + `resume' returns */
584 static int luaB_auxwrap (lua_State
*L
) {
585 lua_State
*co
= lua_tothread(L
, lua_upvalueindex(1));
586 int r
= auxresume(L
, co
, lua_gettop(L
));
588 if (lua_isstring(L
, -1)) { /* error object is a string? */
589 luaL_where(L
, 1); /* add extra info */
593 lua_error(L
); /* propagate error */
599 static int luaB_cocreate (lua_State
*L
) {
600 lua_State
*NL
= lua_newthread(L
);
601 luaL_argcheck(L
, lua_isfunction(L
, 1) && !lua_iscfunction(L
, 1), 1,
602 "Lua function expected");
603 lua_pushvalue(L
, 1); /* move function to top */
604 lua_xmove(L
, NL
, 1); /* move function from L to NL */
609 static int luaB_cowrap (lua_State
*L
) {
611 lua_pushcclosure(L
, luaB_auxwrap
, 1);
616 static int luaB_yield (lua_State
*L
) {
617 return lua_yield(L
, lua_gettop(L
));
621 static int luaB_costatus (lua_State
*L
) {
622 lua_State
*co
= lua_tothread(L
, 1);
623 luaL_argcheck(L
, co
, 1, "coroutine expected");
624 if (L
== co
) lua_pushliteral(L
, "running");
627 if (lua_getstack(co
, 0, &ar
) == 0 && lua_gettop(co
) == 0)
628 lua_pushliteral(L
, "dead");
630 lua_pushliteral(L
, "suspended");
636 static const luaL_reg co_funcs
[] = {
637 {"create", luaB_cocreate
},
638 {"wrap", luaB_cowrap
},
639 {"resume", luaB_coresume
},
640 {"yield", luaB_yield
},
641 {"status", luaB_costatus
},
645 /* }====================================================== */
649 static void base_open (lua_State
*L
) {
650 lua_pushliteral(L
, "_G");
651 lua_pushvalue(L
, LUA_GLOBALSINDEX
);
652 luaL_openlib(L
, NULL
, base_funcs
, 0); /* open lib into global table */
653 lua_pushliteral(L
, "_VERSION");
654 lua_pushliteral(L
, LUA_VERSION
);
655 lua_rawset(L
, -3); /* set global _VERSION */
656 /* `newproxy' needs a weaktable as upvalue */
657 lua_pushliteral(L
, "newproxy");
658 lua_newtable(L
); /* new table `w' */
659 lua_pushvalue(L
, -1); /* `w' will be its own metatable */
660 lua_setmetatable(L
, -2);
661 lua_pushliteral(L
, "__mode");
662 lua_pushliteral(L
, "k");
663 lua_rawset(L
, -3); /* metatable(w).__mode = "k" */
664 lua_pushcclosure(L
, luaB_newproxy
, 1);
665 lua_rawset(L
, -3); /* set global `newproxy' */
666 lua_rawset(L
, -1); /* set global _G */
670 LUALIB_API
int luaopen_base (lua_State
*L
) {
672 luaL_openlib(L
, LUA_COLIBNAME
, co_funcs
, 0);
674 lua_setglobal(L
, REQTAB
);