I would like to print a list of all environment variables and their values. I searched the Stackoverflow and the following questions come close but don't answer me:
Unlike C, Lua doesn't have envp**
parameter that's passed to main()
so I couldn't find a way to get a list of all environment variables. Does anybody know how I can get the list of the name and value of all environment variables?
Standard Lua functions are based on C-standard functions, and there is no C-standard function to get all the environment variables. Therefore, there is no Lua standard function to do it either.
You will have to use a module like luaex, which provides this functionality.
This code was extracted from an old POSIX binding.
static int Pgetenv(lua_State *L) /** getenv([name]) */
{
if (lua_isnone(L, 1))
{
extern char **environ;
char **e;
if (*environ==NULL) lua_pushnil(L); else lua_newtable(L);
for (e=environ; *e!=NULL; e++)
{
char *s=*e;
char *eq=strchr(s, '=');
if (eq==NULL) /* will this ever happen? */
{
lua_pushstring(L,s);
lua_pushboolean(L,0);
}
else
{
lua_pushlstring(L,s,eq-s);
lua_pushstring(L,eq+1);
}
lua_settable(L,-3);
}
}
else
lua_pushstring(L, getenv(luaL_checkstring(L, 1)));
return 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With