* new project: ff-luci - Freifunk Lua Configuration Interface
[project/luci.git] / src / ffluci / util.lua
1 --[[
2 FFLuCI - Utility library
3
4 Description:
5 Several common useful Lua functions
6
7 FileId:
8 $Id$
9
10 License:
11 Copyright 2008 Steven Barth <steven@midlink.org>
12
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
16
17 http://www.apache.org/licenses/LICENSE-2.0
18
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
24
25 ]]--
26
27 module("ffluci.util", package.seeall)
28
29 -- Checks whether a table has an object "value" in it
30 function contains(table, value)
31 for k,v in pairs(table) do
32 if value == v then
33 return true
34 end
35 end
36 return false
37 end
38
39
40 -- Dumps a table to stdout (useful for testing and debugging)
41 function dumptable(t, i)
42 i = i or 0
43 for k,v in pairs(t) do
44 print(string.rep("\t", i) .. k, v)
45 if type(v) == "table" then
46 dumptable(v, i+1)
47 end
48 end
49 end
50
51
52 -- Escapes all occurences of c in s
53 function escape(s, c)
54 c = c or "\\"
55 return s:gsub(c, "\\" .. c)
56 end
57
58
59 -- Runs "command" and returns its output
60 function exec(command, return_array)
61 local pp = io.popen(command)
62 local data = nil
63
64 if return_array then
65 local line = ""
66 data = {}
67
68 while true do
69 line = pp:read()
70 if (line == nil) then break end
71 table.insert(data, line)
72 end
73 pp:close()
74 else
75 data = pp:read("*a")
76 pp:close()
77 end
78
79 return data
80 end
81
82 -- Populate obj in the scope of f as key
83 function extfenv(f, key, obj)
84 local scope = getfenv(f)
85 scope[key] = obj
86 setfenv(f, scope)
87 end
88
89
90 -- Updates the scope of f with "extscope"
91 function updfenv(f, extscope)
92 local scope = getfenv(f)
93 for k, v in pairs(extscope) do
94 scope[k] = v
95 end
96 setfenv(f, scope)
97 end
98
99 -- Returns the filename of the calling script
100 function __file__()
101 return debug.getinfo(2, 'S').source:sub(2)
102 end