Search code examples
lua

Print list of ALL environment variables


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?


Solution

  • 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;
    }