1 /* $NetBSD: lbaselib.c,v 1.5 2015/10/08 13:21:00 mbalmer Exp $ */
4 ** Id: lbaselib.c,v 1.310 2015/03/28 19:14:47 roberto Exp
6 ** See Copyright Notice in lua.h
28 static int luaB_print (lua_State
*L
) {
29 int n
= lua_gettop(L
); /* number of arguments */
31 lua_getglobal(L
, "tostring");
32 for (i
=1; i
<=n
; i
++) {
35 lua_pushvalue(L
, -1); /* function to be called */
36 lua_pushvalue(L
, i
); /* value to print */
38 s
= lua_tolstring(L
, -1, &l
); /* get result */
40 return luaL_error(L
, "'tostring' must return a string to 'print'");
41 if (i
>1) lua_writestring("\t", 1);
42 lua_writestring(s
, l
);
43 lua_pop(L
, 1); /* pop result */
50 #define SPACECHARS " \f\n\r\t\v"
52 static const char *b_str2int (const char *s
, int base
, lua_Integer
*pn
) {
55 s
+= strspn(s
, SPACECHARS
); /* skip initial spaces */
56 if (*s
== '-') { s
++; neg
= 1; } /* handle signal */
57 else if (*s
== '+') s
++;
58 if (!isalnum((unsigned char)*s
)) /* no digit? */
61 int digit
= (isdigit((unsigned char)*s
)) ? *s
- '0'
62 : (toupper((unsigned char)*s
) - 'A') + 10;
63 if (digit
>= base
) return NULL
; /* invalid numeral */
66 } while (isalnum((unsigned char)*s
));
67 s
+= strspn(s
, SPACECHARS
); /* skip trailing spaces */
68 *pn
= (lua_Integer
)((neg
) ? (0u - n
) : n
);
73 static int luaB_tonumber (lua_State
*L
) {
74 if (lua_isnoneornil(L
, 2)) { /* standard conversion? */
76 if (lua_type(L
, 1) == LUA_TNUMBER
) { /* already a number? */
77 lua_settop(L
, 1); /* yes; return it */
82 const char *s
= lua_tolstring(L
, 1, &l
);
83 if (s
!= NULL
&& lua_stringtonumber(L
, s
) == l
+ 1)
84 return 1; /* successful conversion to number */
85 /* else not a number */
91 lua_Integer n
= 0; /* to avoid warnings */
92 lua_Integer base
= luaL_checkinteger(L
, 2);
93 luaL_checktype(L
, 1, LUA_TSTRING
); /* before 'luaL_checklstring'! */
94 s
= luaL_checklstring(L
, 1, &l
);
95 luaL_argcheck(L
, 2 <= base
&& base
<= 36, 2, "base out of range");
96 if (b_str2int(s
, (int)base
, &n
) == s
+ l
) {
97 lua_pushinteger(L
, n
);
99 } /* else not a number */
100 } /* else not a number */
101 lua_pushnil(L
); /* not a number */
106 static int luaB_error (lua_State
*L
) {
107 int level
= (int)luaL_optinteger(L
, 2, 1);
109 if (lua_isstring(L
, 1) && level
> 0) { /* add extra information? */
110 luaL_where(L
, level
);
118 static int luaB_getmetatable (lua_State
*L
) {
120 if (!lua_getmetatable(L
, 1)) {
122 return 1; /* no metatable */
124 luaL_getmetafield(L
, 1, "__metatable");
125 return 1; /* returns either __metatable field (if present) or metatable */
129 static int luaB_setmetatable (lua_State
*L
) {
130 int t
= lua_type(L
, 2);
131 luaL_checktype(L
, 1, LUA_TTABLE
);
132 luaL_argcheck(L
, t
== LUA_TNIL
|| t
== LUA_TTABLE
, 2,
133 "nil or table expected");
134 if (luaL_getmetafield(L
, 1, "__metatable") != LUA_TNIL
)
135 return luaL_error(L
, "cannot change a protected metatable");
137 lua_setmetatable(L
, 1);
142 static int luaB_rawequal (lua_State
*L
) {
145 lua_pushboolean(L
, lua_rawequal(L
, 1, 2));
150 static int luaB_rawlen (lua_State
*L
) {
151 int t
= lua_type(L
, 1);
152 luaL_argcheck(L
, t
== LUA_TTABLE
|| t
== LUA_TSTRING
, 1,
153 "table or string expected");
154 lua_pushinteger(L
, lua_rawlen(L
, 1));
159 static int luaB_rawget (lua_State
*L
) {
160 luaL_checktype(L
, 1, LUA_TTABLE
);
167 static int luaB_rawset (lua_State
*L
) {
168 luaL_checktype(L
, 1, LUA_TTABLE
);
177 static int luaB_collectgarbage (lua_State
*L
) {
178 static const char *const opts
[] = {"stop", "restart", "collect",
179 "count", "step", "setpause", "setstepmul",
181 static const int optsnum
[] = {LUA_GCSTOP
, LUA_GCRESTART
, LUA_GCCOLLECT
,
182 LUA_GCCOUNT
, LUA_GCSTEP
, LUA_GCSETPAUSE
, LUA_GCSETSTEPMUL
,
184 int o
= optsnum
[luaL_checkoption(L
, 1, "collect", opts
)];
185 int ex
= (int)luaL_optinteger(L
, 2, 0);
186 int res
= lua_gc(L
, o
, ex
);
189 int b
= lua_gc(L
, LUA_GCCOUNTB
, 0);
190 lua_pushnumber(L
, (lua_Number
)res
+ ((lua_Number
)b
/1024));
193 case LUA_GCSTEP
: case LUA_GCISRUNNING
: {
194 lua_pushboolean(L
, res
);
198 lua_pushinteger(L
, res
);
206 ** This function has all type names as upvalues, to maximize performance.
208 static int luaB_type (lua_State
*L
) {
210 lua_pushvalue(L
, lua_upvalueindex(lua_type(L
, 1) + 1));
215 static int pairsmeta (lua_State
*L
, const char *method
, int iszero
,
216 lua_CFunction iter
) {
217 if (luaL_getmetafield(L
, 1, method
) == LUA_TNIL
) { /* no metamethod? */
218 luaL_checktype(L
, 1, LUA_TTABLE
); /* argument must be a table */
219 lua_pushcfunction(L
, iter
); /* will return generator, */
220 lua_pushvalue(L
, 1); /* state, */
221 if (iszero
) lua_pushinteger(L
, 0); /* and initial value */
225 lua_pushvalue(L
, 1); /* argument 'self' to metamethod */
226 lua_call(L
, 1, 3); /* get 3 values from metamethod */
232 static int luaB_next (lua_State
*L
) {
233 luaL_checktype(L
, 1, LUA_TTABLE
);
234 lua_settop(L
, 2); /* create a 2nd argument if there isn't one */
244 static int luaB_pairs (lua_State
*L
) {
245 return pairsmeta(L
, "__pairs", 0, luaB_next
);
250 ** Traversal function for 'ipairs' for raw tables
252 static int ipairsaux_raw (lua_State
*L
) {
253 lua_Integer i
= luaL_checkinteger(L
, 2) + 1;
254 luaL_checktype(L
, 1, LUA_TTABLE
);
255 lua_pushinteger(L
, i
);
256 return (lua_rawgeti(L
, 1, i
) == LUA_TNIL
) ? 1 : 2;
261 ** Traversal function for 'ipairs' for tables with metamethods
263 static int ipairsaux (lua_State
*L
) {
264 lua_Integer i
= luaL_checkinteger(L
, 2) + 1;
265 lua_pushinteger(L
, i
);
266 return (lua_geti(L
, 1, i
) == LUA_TNIL
) ? 1 : 2;
271 ** This function will use either 'ipairsaux' or 'ipairsaux_raw' to
272 ** traverse a table, depending on whether the table has metamethods
273 ** that can affect the traversal.
275 static int luaB_ipairs (lua_State
*L
) {
276 lua_CFunction iter
= (luaL_getmetafield(L
, 1, "__index") != LUA_TNIL
)
277 ? ipairsaux
: ipairsaux_raw
;
278 #if defined(LUA_COMPAT_IPAIRS)
279 return pairsmeta(L
, "__ipairs", 1, iter
);
282 lua_pushcfunction(L
, iter
); /* iteration function */
283 lua_pushvalue(L
, 1); /* state */
284 lua_pushinteger(L
, 0); /* initial value */
290 static int load_aux (lua_State
*L
, int status
, int envidx
) {
291 if (status
== LUA_OK
) {
292 if (envidx
!= 0) { /* 'env' parameter? */
293 lua_pushvalue(L
, envidx
); /* environment for loaded function */
294 if (!lua_setupvalue(L
, -2, 1)) /* set it as 1st upvalue */
295 lua_pop(L
, 1); /* remove 'env' if not used by previous call */
299 else { /* error (message is on top of the stack) */
301 lua_insert(L
, -2); /* put before error message */
302 return 2; /* return nil plus error message */
308 static int luaB_loadfile (lua_State
*L
) {
309 const char *fname
= luaL_optstring(L
, 1, NULL
);
310 const char *mode
= luaL_optstring(L
, 2, NULL
);
311 int env
= (!lua_isnone(L
, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */
312 int status
= luaL_loadfilex(L
, fname
, mode
);
313 return load_aux(L
, status
, env
);
319 ** {======================================================
320 ** Generic Read function
321 ** =======================================================
326 ** reserved slot, above all arguments, to hold a copy of the returned
327 ** string to avoid it being collected while parsed. 'load' has four
328 ** optional arguments (chunk, source name, mode, and environment).
330 #define RESERVEDSLOT 5
334 ** Reader for generic 'load' function: 'lua_load' uses the
335 ** stack for internal stuff, so the reader cannot change the
336 ** stack top. Instead, it keeps its resulting string in a
337 ** reserved slot inside the stack.
339 static const char *generic_reader (lua_State
*L
, void *ud
, size_t *size
) {
340 (void)(ud
); /* not used */
341 luaL_checkstack(L
, 2, "too many nested functions");
342 lua_pushvalue(L
, 1); /* get function */
343 lua_call(L
, 0, 1); /* call it */
344 if (lua_isnil(L
, -1)) {
345 lua_pop(L
, 1); /* pop result */
349 else if (!lua_isstring(L
, -1))
350 luaL_error(L
, "reader function must return a string");
351 lua_replace(L
, RESERVEDSLOT
); /* save string in reserved slot */
352 return lua_tolstring(L
, RESERVEDSLOT
, size
);
356 static int luaB_load (lua_State
*L
) {
359 const char *s
= lua_tolstring(L
, 1, &l
);
360 const char *mode
= luaL_optstring(L
, 3, "bt");
361 int env
= (!lua_isnone(L
, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */
362 if (s
!= NULL
) { /* loading a string? */
363 const char *chunkname
= luaL_optstring(L
, 2, s
);
364 status
= luaL_loadbufferx(L
, s
, l
, chunkname
, mode
);
366 else { /* loading from a reader function */
367 const char *chunkname
= luaL_optstring(L
, 2, "=(load)");
368 luaL_checktype(L
, 1, LUA_TFUNCTION
);
369 lua_settop(L
, RESERVEDSLOT
); /* create reserved slot */
370 status
= lua_load(L
, generic_reader
, NULL
, chunkname
, mode
);
372 return load_aux(L
, status
, env
);
375 /* }====================================================== */
379 static int dofilecont (lua_State
*L
, int d1
, lua_KContext d2
) {
380 (void)d1
; (void)d2
; /* only to match 'lua_Kfunction' prototype */
381 return lua_gettop(L
) - 1;
385 static int luaB_dofile (lua_State
*L
) {
386 const char *fname
= luaL_optstring(L
, 1, NULL
);
388 if (luaL_loadfile(L
, fname
) != LUA_OK
)
390 lua_callk(L
, 0, LUA_MULTRET
, 0, dofilecont
);
391 return dofilecont(L
, 0, 0);
396 static int luaB_assert (lua_State
*L
) {
397 if (lua_toboolean(L
, 1)) /* condition is true? */
398 return lua_gettop(L
); /* return all arguments */
400 luaL_checkany(L
, 1); /* there must be a condition */
401 lua_remove(L
, 1); /* remove it */
402 lua_pushliteral(L
, "assertion failed!"); /* default message */
403 lua_settop(L
, 1); /* leave only message (default if no other one) */
404 return luaB_error(L
); /* call 'error' */
409 static int luaB_select (lua_State
*L
) {
410 int n
= lua_gettop(L
);
411 if (lua_type(L
, 1) == LUA_TSTRING
&& *lua_tostring(L
, 1) == '#') {
412 lua_pushinteger(L
, n
-1);
416 lua_Integer i
= luaL_checkinteger(L
, 1);
417 if (i
< 0) i
= n
+ i
;
418 else if (i
> n
) i
= n
;
419 luaL_argcheck(L
, 1 <= i
, 1, "index out of range");
426 ** Continuation function for 'pcall' and 'xpcall'. Both functions
427 ** already pushed a 'true' before doing the call, so in case of success
428 ** 'finishpcall' only has to return everything in the stack minus
429 ** 'extra' values (where 'extra' is exactly the number of items to be
432 static int finishpcall (lua_State
*L
, int status
, lua_KContext extra
) {
433 if (status
!= LUA_OK
&& status
!= LUA_YIELD
) { /* error? */
434 lua_pushboolean(L
, 0); /* first result (false) */
435 lua_pushvalue(L
, -2); /* error message */
436 return 2; /* return false, msg */
439 return lua_gettop(L
) - (int)extra
; /* return all results */
443 static int luaB_pcall (lua_State
*L
) {
446 lua_pushboolean(L
, 1); /* first result if no errors */
447 lua_insert(L
, 1); /* put it in place */
448 status
= lua_pcallk(L
, lua_gettop(L
) - 2, LUA_MULTRET
, 0, 0, finishpcall
);
449 return finishpcall(L
, status
, 0);
454 ** Do a protected call with error handling. After 'lua_rotate', the
455 ** stack will have <f, err, true, f, [args...]>; so, the function passes
456 ** 2 to 'finishpcall' to skip the 2 first values when returning results.
458 static int luaB_xpcall (lua_State
*L
) {
460 int n
= lua_gettop(L
);
461 luaL_checktype(L
, 2, LUA_TFUNCTION
); /* check error function */
462 lua_pushboolean(L
, 1); /* first result */
463 lua_pushvalue(L
, 1); /* function */
464 lua_rotate(L
, 3, 2); /* move them below function's arguments */
465 status
= lua_pcallk(L
, n
- 2, LUA_MULTRET
, 2, 2, finishpcall
);
466 return finishpcall(L
, status
, 2);
470 static int luaB_tostring (lua_State
*L
) {
472 luaL_tolstring(L
, 1, NULL
);
477 static const luaL_Reg base_funcs
[] = {
478 {"assert", luaB_assert
},
479 {"collectgarbage", luaB_collectgarbage
},
481 {"dofile", luaB_dofile
},
483 {"error", luaB_error
},
484 {"getmetatable", luaB_getmetatable
},
485 {"ipairs", luaB_ipairs
},
487 {"loadfile", luaB_loadfile
},
490 #if defined(LUA_COMPAT_LOADSTRING)
491 {"loadstring", luaB_load
},
494 {"pairs", luaB_pairs
},
495 {"pcall", luaB_pcall
},
496 {"print", luaB_print
},
497 {"rawequal", luaB_rawequal
},
498 {"rawlen", luaB_rawlen
},
499 {"rawget", luaB_rawget
},
500 {"rawset", luaB_rawset
},
501 {"select", luaB_select
},
502 {"setmetatable", luaB_setmetatable
},
503 {"tonumber", luaB_tonumber
},
504 {"tostring", luaB_tostring
},
505 {"xpcall", luaB_xpcall
},
514 LUAMOD_API
int luaopen_base (lua_State
*L
) {
516 /* open lib into global table */
517 lua_pushglobaltable(L
);
518 luaL_setfuncs(L
, base_funcs
, 0);
520 lua_pushvalue(L
, -1);
521 lua_setfield(L
, -2, "_G");
522 /* set global _VERSION */
523 lua_pushliteral(L
, LUA_VERSION
);
524 lua_setfield(L
, -2, "_VERSION");
525 /* set function 'type' with proper upvalues */
526 for (i
= 0; i
< LUA_NUMTAGS
; i
++) /* push all type names as upvalues */
527 lua_pushstring(L
, lua_typename(L
, i
));
528 lua_pushcclosure(L
, luaB_type
, LUA_NUMTAGS
);
529 lua_setfield(L
, -2, "type");