Reading Iguana Environment Variables with os.getenv()

This can be a helpful way of changing the behaviour of scripts based on the server they are running on.

This example  logs an error message that includes the absolute pathname of a file. The file is located in the file_in sub-directory of the Iguana working directory. however the Iguana working directory on the production server is different from the development server. So if we hard-coded the path we would need to change the code when we release it (not good practice). The solution is quite simple we just add the value of the iguana_dir environment variable (which contains the Iguana working directory) to the beginning of the relative filename.

Take a simple example where you have a channel that reads files from the file_in sub-directory of the Iguana working directory. The best way to access this directory from a Lua script is to use the relative directory name “\file_in” when reading files from the directory:

   local h = io.open('\file_in\test')
   h:read()
   -- etc...

Let’s say that you get an error reading the file and want to log an error message, but you want to write the absolute filepath in the message (because the administrator may not know the Iguana working directory).

Simple:

   local h, err = io.open('\\file_in\\test')
   if err then
      iguana.logError('ERROR reading file '..err)                          -- logs relative path
      iguana.logError('ERROR reading file '..os.getenv('iguana_dir')..err) -- logs absolute path (by prepending the Iguana working directory)
   else
      h:read()
      -- etc...
   end

Leave A Comment?