Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print list of ALL environment variables

Tags:

lua

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:

  • How to discover what is available in lua environment? (it's about Lua environment not the system environment variables)
  • Print all local variables accessible to the current scope in Lua (again about _G not the os environment variables)
  • http://www.lua.org/manual/5.1/manual.html#pdf-os.getenv (this is a good function but I have to know the name of the environment variable in order to call it)

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?

like image 759
AlexStack Avatar asked Oct 03 '11 09:10

AlexStack


2 Answers

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.

like image 159
Nicol Bolas Avatar answered Sep 28 '22 15:09

Nicol Bolas


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;
}
like image 33
lhf Avatar answered Sep 28 '22 15:09

lhf