2 FFLuCI - Utility library
5 Several common useful Lua functions
11 Copyright 2008 Steven Barth <steven@midlink.org>
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
17 http://www.apache.org/licenses/LICENSE-2.0
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.
27 module("ffluci.util", package.seeall)
30 -- Lua simplified Python-style OO class support emulation
34 local create = function(class, ...)
36 setmetatable(inst, {__index = class})
39 local stat, err = pcall(inst.__init__, inst, ...)
48 local classmeta = {__call = create}
51 classmeta.__index = base
54 setmetatable(class, classmeta)
59 -- Checks whether a table has an object "value" in it
60 function contains(table, value)
61 for k,v in pairs(table) do
70 -- Dumps a table to stdout (useful for testing and debugging)
71 function dumptable(t, i)
73 for k,v in pairs(t) do
74 print(string.rep("\t", i) .. k, v)
75 if type(v) == "table" then
82 -- Escapes all occurences of c in s
85 return s:gsub(c, "\\" .. c)
89 -- Runs "command" and returns its output
90 function exec(command)
91 local pp = io.popen(command)
92 local data = pp:read("*a")
99 -- Runs "command" and returns its output as a array of lines
100 function execl(command)
101 local pp = io.popen(command)
107 if (line == nil) then break end
108 table.insert(data, line)
116 -- Populate obj in the scope of f as key
117 function extfenv(f, key, obj)
118 local scope = getfenv(f)
123 -- Checks whether an object is an instanceof class
124 function instanceof(object, class)
125 local meta = getmetatable(object)
126 while meta and meta.__index do
127 if meta.__index == class then
130 meta = getmetatable(meta.__index)
136 -- Resets the scope of f doing a shallow copy of its scope into a new table
138 local scope = getfenv(f)
144 -- Returns the Haserl unique sessionid
149 -- Updates the scope of f with "extscope"
150 function updfenv(f, extscope)
151 local scope = getfenv(f)
152 for k, v in pairs(extscope) do
158 -- Validates a variable
159 function validate(value, valid, cast_number, cast_int)
160 if cast_number or cast_int then
161 value = tonumber(value)
164 if cast_int and value and not(value % 1 == 0) then
169 if type(valid) == "function" then
171 elseif type(valid) == "table" then
172 if not contains(valid, value) then
181 -- Returns the filename of the calling script
183 return debug.getinfo(2, 'S').source:sub(2)