root/HTTP/Config.lua

Revision 1379 (checked in by rsz, 6 months ago)

cleanup

Line 
1 --------------------------------------------------------------------------------
2 -- Title:               Config.lua
3 -- Description:         Like a square peg in a round hole
4 -- Author:              Raphaël Szwarc http://alt.textdrive.com/lua/
5 -- Creation Date:       January 30, 2007
6 -- Legal:               Copyright (C) 2007 Raphaël Szwarc
7 --                      Under the terms of the MIT License
8 --                      http://www.opensource.org/licenses/mit-license.html
9 --------------------------------------------------------------------------------
10
11 -- import dependencies
12 local io = require( 'io' )
13 local table = require( 'table' )
14
15 local assert = assert
16 local getmetatable = getmetatable
17 local loadstring = loadstring
18 local setfenv = setfenv
19 local setmetatable = setmetatable
20 local tostring = tostring
21
22 --------------------------------------------------------------------------------
23 -- Config
24 --------------------------------------------------------------------------------
25
26 module( 'Config' )
27 _VERSION = '1.0'
28
29 local self = setmetatable( _M, {} )
30 local meta = getmetatable( self )
31
32 --------------------------------------------------------------------------------
33 -- Utilities
34 --------------------------------------------------------------------------------
35
36 local function Trim( aValue )
37     return ( aValue:gsub( '^[%c%s]+', '' ):gsub( '[%s%c]+$', '' ) )
38 end
39
40 local function Format( aValue )
41     local aBuffer = {}
42    
43     for aLine in aValue:gmatch( '(%C+)' ) do
44         aLine = Trim( aLine )
45        
46         if aLine:len() > 0 then
47             aBuffer[ #aBuffer + 1 ] = aLine
48         end
49     end
50    
51     return ( 'return { %s }' ):format( table.concat( aBuffer, ',\n' ) )
52 end
53
54 local function Read( aValue )
55     local aValue = Format( aValue )
56     local aChunk = assert( loadstring( aValue ) )
57    
58     setfenv( aChunk, {} )
59    
60     return aChunk()
61 end
62
63 --------------------------------------------------------------------------------
64 -- Metamethods
65 --------------------------------------------------------------------------------
66
67 function meta:__call( aValue )
68     return Read( tostring( aValue ) )
69 end
70
71 function meta:__index( aKey )
72     local aFile = assert( io.open( aKey, 'rb' ) )
73     local aContent = aFile:read( '*a' )
74    
75     aFile:close()
76
77     return self( aContent )
78 end
79
80 function meta:__concat( aValue )
81     return tostring( self ) .. tostring( aValue )
82 end
83
84 function meta:__tostring()
85     return ( '%s/%s' ):format( self._NAME, self._VERSION )
86 end
87
88
Note: See TracBrowser for help on using the browser.