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 local io = require "io"
28 local math = require "math"
29 local table = require "table"
30 local debug = require "debug"
31 local ldebug = require "luci.debug"
32 local string = require "string"
33 local coroutine = require "coroutine"
34 local cutil = require "luci.cutil"
36 local getmetatable, setmetatable = getmetatable, setmetatable
37 local rawget, rawset, unpack = rawget, rawset, unpack
38 local tostring, type, assert = tostring, type, assert
39 local ipairs, pairs, loadstring = ipairs, pairs, loadstring
40 local require, pcall, xpcall = require, pcall, xpcall
42 --- LuCI utility functions.
46 -- Pythonic string formatting extension
49 getmetatable("").__mod = function(a, b)
52 elseif type(b) == "table" then
53 return a:format(unpack(b))
62 -- Class helper routines
65 -- Instantiates a class
67 local function _instantiate(class, ...)
68 local inst = setmetatable({}, {__index = class})
78 --- Create a Class object (Python-style object model).
79 -- The class object can be instantiated by calling itself.
80 -- Any class functions or shared parameters can be attached to this object.
81 -- Attaching a table to the class object makes this table shared between
82 -- all instances of this class. For object parameters use the __init__ function.
83 -- Classes can inherit member functions and values from a base class.
84 -- Class can be instantiated by calling them. All parameters will be passed
85 -- to the __init__ function of this class - if such a function exists.
86 -- The __init__ function must be used to set any object parameters that are not shared
87 -- with other objects of this class. Any return values will be ignored.
88 -- @param base The base class to inherit from (optional)
89 -- @return A class object
94 return setmetatable({}, {
95 __call = _instantiate,
102 --- Test whether the given object is an instance of the given class.
103 -- @param object Object instance
104 -- @param class Class object to test against
105 -- @return Boolean indicating whether the object is an instance
108 function instanceof(object, class)
109 local meta = getmetatable(object)
110 while meta and meta.__index do
111 if meta.__index == class then
114 meta = getmetatable(meta.__index)
121 -- Scope manipulation routines
124 --- Create a new or get an already existing thread local store associated with
125 -- the current active coroutine. A thread local store is private a table object
126 -- whose values can't be accessed from outside of the running coroutine.
127 -- @return Table value representing the corresponding thread local store
128 function threadlocal()
131 local function get(self, key)
132 local c = coroutine.running()
133 local thread = coxpt[c] or c or 0
134 if not rawget(self, thread) then
137 return rawget(self, thread)[key]
140 local function set(self, key, value)
141 local c = coroutine.running()
142 local thread = coxpt[c] or c or 0
143 if not rawget(self, thread) then
144 rawset(self, thread, {})
146 rawget(self, thread)[key] = value
149 setmetatable(tbl, {__index = get, __newindex = set, __mode = "k"})
156 -- Debugging routines
159 --- Write given object to stderr.
160 -- @param obj Value to write to stderr
161 -- @return Boolean indicating whether the write operation was successful
163 return io.stderr:write(tostring(obj) .. "\n")
166 --- Recursively dumps a table to stdout, useful for testing and debugging.
167 -- @param t Table value to dump
168 -- @param maxdepth Maximum depth
169 -- @return Always nil
170 function dumptable(t, maxdepth, i, seen)
172 seen = seen or setmetatable({}, {__mode="k"})
174 for k,v in pairs(t) do
175 perror(string.rep("\t", i) .. tostring(k) .. "\t" .. tostring(v))
176 if type(v) == "table" and (not maxdepth or i < maxdepth) then
179 dumptable(v, maxdepth, i+1, seen)
181 perror(string.rep("\t", i) .. "*** RECURSION ***")
189 -- String and data manipulation routines
192 --- Escapes all occurrences of the given character in given string.
193 -- @param s String value containing unescaped characters
194 -- @param c String value with character to escape (optional, defaults to "\")
195 -- @return String value with each occurrence of character escaped with "\"
196 function escape(s, c)
198 return s:gsub(c, "\\" .. c)
201 --- Create valid XML PCDATA from given string.
202 -- @param value String value containing the data to escape
203 -- @return String value containing the escaped data
204 function pcdata(value)
205 return value and tostring(value):gsub("[&\"'<>]", {
214 --- Strip HTML tags from given string.
215 -- @param value String containing the HTML text
216 -- @return String with HTML tags stripped of
217 function striptags(s)
218 return pcdata(s:gsub("</?[A-Za-z][A-Za-z0-9:_%-]*[^>]*>", " "):gsub("%s+", " "))
221 --- Splits given string on a defined separator sequence and return a table
222 -- containing the resulting substrings. The optional max parameter specifies
223 -- the number of bytes to process, regardless of the actual length of the given
224 -- string. The optional last parameter, regex, specifies whether the separator
225 -- sequence is interpreted as regular expression.
226 -- @param str String value containing the data to split up
227 -- @param pat String with separator pattern (optional, defaults to "\n")
228 -- @param max Maximum times to split (optional)
229 -- @param regex Boolean indicating whether to interpret the separator
230 -- pattern as regular expression (optional, default is false)
231 -- @return Table containing the resulting substrings
232 function split(str, pat, max, regex)
252 local s, e = str:find(pat, c, not regex)
254 if s and max < 0 then
257 t[#t+1] = str:sub(c, s and s - 1)
259 c = e and e + 1 or #str + 1
260 until not s or max < 0
265 --- Remove leading and trailing whitespace from given string value.
266 -- @param str String value containing whitespace padded data
267 -- @return String value with leading and trailing space removed
269 return (str:gsub("^%s*(.-)%s*$", "%1"))
272 --- Count the occurences of given substring in given string.
273 -- @param str String to search in
274 -- @param pattern String containing pattern to find
275 -- @return Number of found occurences
276 function cmatch(str, pat)
278 for _ in str:gmatch(pat) do count = count + 1 end
282 --- Parse certain units from the given string and return the canonical integer
283 -- value or 0 if the unit is unknown. Upper- or lower case is irrelevant.
284 -- Recognized units are:
285 -- o "y" - one year (60*60*24*366)
286 -- o "m" - one month (60*60*24*31)
287 -- o "w" - one week (60*60*24*7)
288 -- o "d" - one day (60*60*24)
289 -- o "h" - one hour (60*60)
290 -- o "min" - one minute (60)
291 -- o "kb" - one kilobyte (1024)
292 -- o "mb" - one megabyte (1024*1024)
293 -- o "gb" - one gigabyte (1024*1024*1024)
294 -- o "kib" - one si kilobyte (1000)
295 -- o "mib" - one si megabyte (1000*1000)
296 -- o "gib" - one si gigabyte (1000*1000*1000)
297 -- @param ustr String containing a numerical value with trailing unit
298 -- @return Number containing the canonical value
299 function parse_units(ustr)
306 y = 60 * 60 * 24 * 366,
307 m = 60 * 60 * 24 * 31,
308 w = 60 * 60 * 24 * 7,
316 gb = 1024 * 1024 * 1024,
318 -- storage sizes (si)
321 gib = 1000 * 1000 * 1000
324 -- parse input string
325 for spec in ustr:lower():gmatch("[0-9%.]+[a-zA-Z]*") do
327 local num = spec:gsub("[^0-9%.]+$","")
328 local spn = spec:gsub("^[0-9%.]+", "")
330 if map[spn] or map[spn:sub(1,1)] then
331 val = val + num * ( map[spn] or map[spn:sub(1,1)] )
341 -- also register functions above in the central string class for convenience
342 string.escape = escape
343 string.pcdata = pcdata
344 string.striptags = striptags
347 string.cmatch = cmatch
348 string.parse_units = parse_units
351 --- Appends numerically indexed tables or single objects to a given table.
352 -- @param src Target table
353 -- @param ... Objects to insert
354 -- @return Target table
355 function append(src, ...)
356 for i, a in ipairs({...}) do
357 if type(a) == "table" then
358 for j, v in ipairs(a) do
368 --- Combines two or more numerically indexed tables and single objects into one table.
369 -- @param tbl1 Table value to combine
370 -- @param tbl2 Table value to combine
371 -- @param ... More tables to combine
372 -- @return Table value containing all values of given tables
373 function combine(...)
374 return append({}, ...)
377 --- Checks whether the given table contains the given value.
378 -- @param table Table value
379 -- @param value Value to search within the given table
380 -- @return Boolean indicating whether the given value occurs within table
381 function contains(table, value)
382 for k, v in pairs(table) do
390 --- Update values in given table with the values from the second given table.
391 -- Both table are - in fact - merged together.
392 -- @param t Table which should be updated
393 -- @param updates Table containing the values to update
394 -- @return Always nil
395 function update(t, updates)
396 for k, v in pairs(updates) do
401 --- Retrieve all keys of given associative table.
402 -- @param t Table to extract keys from
403 -- @return Sorted table containing the keys
407 for k, _ in kspairs(t) do
414 --- Clones the given object and return it's copy.
415 -- @param object Table value to clone
416 -- @param deep Boolean indicating whether to do recursive cloning
417 -- @return Cloned table value
418 function clone(object, deep)
421 for k, v in pairs(object) do
422 if deep and type(v) == "table" then
428 return setmetatable(copy, getmetatable(object))
432 --- Create a dynamic table which automatically creates subtables.
433 -- @return Dynamic Table
435 return setmetatable({}, { __index =
437 return rawget(tbl, key)
438 or rawget(rawset(tbl, key, dtable()), key)
444 -- Serialize the contents of a table value.
445 function _serialize_table(t, seen)
446 assert(not seen[t], "Recursion detected.")
453 for k, v in pairs(t) do
454 if type(k) ~= "number" or k < 1 or math.floor(k) ~= k or ( k - #t ) > 3 then
455 k = serialize_data(k, seen)
456 v = serialize_data(v, seen)
457 data = data .. ( #data > 0 and ", " or "" ) ..
458 '[' .. k .. '] = ' .. v
465 local v = serialize_data(t[i], seen)
466 idata = idata .. ( #idata > 0 and ", " or "" ) .. v
469 return idata .. ( #data > 0 and #idata > 0 and ", " or "" ) .. data
472 --- Recursively serialize given data to lua code, suitable for restoring
473 -- with loadstring().
474 -- @param val Value containing the data to serialize
475 -- @return String value containing the serialized code
478 function serialize_data(val, seen)
479 seen = seen or setmetatable({}, {__mode="k"})
483 elseif type(val) == "number" then
485 elseif type(val) == "string" then
487 elseif type(val) == "boolean" then
488 return val and "true" or "false"
489 elseif type(val) == "function" then
490 return "loadstring(%q)" % get_bytecode(val)
491 elseif type(val) == "table" then
492 return "{ " .. _serialize_table(val, seen) .. " }"
494 return '"[unhandled data type:' .. type(val) .. ']"'
498 --- Restore data previously serialized with serialize_data().
499 -- @param str String containing the data to restore
500 -- @return Value containing the restored data structure
501 -- @see serialize_data
503 function restore_data(str)
504 return loadstring("return " .. str)()
509 -- Byte code manipulation routines
512 --- Return the current runtime bytecode of the given data. The byte code
513 -- will be stripped before it is returned.
514 -- @param val Value to return as bytecode
515 -- @return String value containing the bytecode of the given data
516 function get_bytecode(val)
519 if type(val) == "function" then
520 code = string.dump(val)
522 code = string.dump( loadstring( "return " .. serialize_data(val) ) )
525 return code and strip_bytecode(code)
528 --- Strips unnescessary lua bytecode from given string. Information like line
529 -- numbers and debugging numbers will be discarded. Original version by
530 -- Peter Cawley (http://lua-users.org/lists/lua-l/2008-02/msg01158.html)
531 -- @param code String value containing the original lua byte code
532 -- @return String value containing the stripped lua byte code
533 function strip_bytecode(code)
534 local version, format, endian, int, size, ins, num, lnum = code:byte(5, 12)
537 subint = function(code, i, l)
540 val = val * 256 + code:byte(i + n - 1)
545 subint = function(code, i, l)
548 val = val * 256 + code:byte(i + n - 1)
555 strip_function = function(code)
556 local count, offset = subint(code, 1, size)
557 local stripped, dirty = string.rep("\0", size), offset + count
558 offset = offset + count + int * 2 + 4
559 offset = offset + int + subint(code, offset, int) * ins
560 count, offset = subint(code, offset, int)
563 t, offset = subint(code, offset, 1)
567 offset = offset + size + subint(code, offset, size)
569 offset = offset + num
570 elseif t == 254 or t == 9 then
571 offset = offset + lnum
574 count, offset = subint(code, offset, int)
575 stripped = stripped .. code:sub(dirty, offset - 1)
577 local proto, off = strip_function(code:sub(offset, -1))
578 stripped, offset = stripped .. proto, offset + off - 1
580 offset = offset + subint(code, offset, int) * int + int
581 count, offset = subint(code, offset, int)
583 offset = offset + subint(code, offset, size) + size + int * 2
585 count, offset = subint(code, offset, int)
587 offset = offset + subint(code, offset, size) + size
589 stripped = stripped .. string.rep("\0", int * 3)
590 return stripped, offset
593 return code:sub(1,12) .. strip_function(code:sub(13,-1))
598 -- Sorting iterator functions
601 function _sortiter( t, f )
604 for k, v in pairs(t) do
610 table.sort( keys, f )
614 if _pos <= #keys then
615 return keys[_pos], t[keys[_pos]]
620 --- Return a key, value iterator which returns the values sorted according to
621 -- the provided callback function.
622 -- @param t The table to iterate
623 -- @param f A callback function to decide the order of elements
624 -- @return Function value containing the corresponding iterator
626 return _sortiter( t, f )
629 --- Return a key, value iterator for the given table.
630 -- The table pairs are sorted by key.
631 -- @param t The table to iterate
632 -- @return Function value containing the corresponding iterator
634 return _sortiter( t )
637 --- Return a key, value iterator for the given table.
638 -- The table pairs are sorted by value.
639 -- @param t The table to iterate
640 -- @return Function value containing the corresponding iterator
642 return _sortiter( t, function (a,b) return t[a] < t[b] end )
647 -- System utility functions
650 --- Test whether the current system is operating in big endian mode.
651 -- @return Boolean value indicating whether system is big endian
653 return string.byte(string.dump(function() end), 7) == 0
656 --- Execute given commandline and gather stdout.
657 -- @param command String containing command to execute
658 -- @return String containing the command's stdout
659 function exec(command)
660 local pp = io.popen(command)
661 local data = pp:read("*a")
667 --- Return a line-buffered iterator over the output of given command.
668 -- @param command String containing the command to execute
670 function execi(command)
671 local pp = io.popen(command)
673 return pp and function()
674 local line = pp:read()
685 function execl(command)
686 local pp = io.popen(command)
692 if (line == nil) then break end
700 --- Returns the absolute path to LuCI base directory.
701 -- @return String containing the directory path
703 return require "luci.fs".dirname(ldebug.__file__)
708 -- Coroutine safe xpcall and pcall versions modified for Luci
710 -- coxpcall 1.13 - Copyright 2005 - Kepler Project (www.keplerproject.org)
712 -- Copyright © 2005 Kepler Project.
713 -- Permission is hereby granted, free of charge, to any person obtaining a
714 -- copy of this software and associated documentation files (the "Software"),
715 -- to deal in the Software without restriction, including without limitation
716 -- the rights to use, copy, modify, merge, publish, distribute, sublicense,
717 -- and/or sell copies of the Software, and to permit persons to whom the
718 -- Software is furnished to do so, subject to the following conditions:
720 -- The above copyright notice and this permission notice shall be
721 -- included in all copies or substantial portions of the Software.
723 -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
724 -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
725 -- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
726 -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
727 -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
728 -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
729 -- OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
731 local performResume, handleReturnValue
732 local oldpcall, oldxpcall = pcall, xpcall
734 setmetatable(coxpt, {__mode = "kv"})
736 -- Identity function for copcall
737 local function copcall_id(trace, ...)
741 --- This is a coroutine-safe drop-in replacement for Lua's "xpcall"-function
742 -- @param f Lua function to be called protected
743 -- @param err Custom error handler
744 -- @param ... Parameters passed to the function
745 -- @return A boolean whether the function call succeeded and the return
746 -- values of either the function or the error handler
747 function coxpcall(f, err, ...)
748 local res, co = oldpcall(coroutine.create, f)
751 local newf = function() return f(unpack(params)) end
752 co = coroutine.create(newf)
754 local c = coroutine.running()
755 coxpt[co] = coxpt[c] or c or 0
757 return performResume(err, co, ...)
760 --- This is a coroutine-safe drop-in replacement for Lua's "pcall"-function
761 -- @param f Lua function to be called protected
762 -- @param ... Parameters passed to the function
763 -- @return A boolean whether the function call succeeded and the returns
764 -- values of the function or the error object
765 function copcall(f, ...)
766 return coxpcall(f, copcall_id, ...)
769 -- Handle return value of protected call
770 function handleReturnValue(err, co, status, ...)
772 return false, err(debug.traceback(co, (...)), ...)
774 if coroutine.status(co) == 'suspended' then
775 return performResume(err, co, coroutine.yield(...))
781 -- Resume execution of protected function call
782 function performResume(err, co, ...)
783 return handleReturnValue(err, co, coroutine.resume(co, ...))