summaryrefslogtreecommitdiff
path: root/misc/freeswitch/scripts/common/array.lua
blob: 5683dce66c002542356b1d22fcb2c85cd22f1e99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
-- Gemeinschaft 5 module: array functions
-- (c) AMOOMA GmbH 2013
-- 

module(...,package.seeall)

function try(array, arguments)
  if type(arguments) ~= 'string' or type(array) ~= 'table' then
    return nil;
  end

  local result = array;
  
  arguments:gsub('([^%.]+)', function(entry)
    local success, result = pcall(function() result = (result[tonumber(entry) or entry]); end);
  end);
  
  return result;
end


function set(array, arguments, value)
  local nop, arguments_count = arguments:gsub('%.', '');
  local structure = array;
  arguments:gsub('([^%.]+)', function(entry)
    if arguments_count <= 0 then
      structure[entry] = value;
    elseif type(structure[entry]) == 'table' then
      structure = structure[entry];
    else
      structure[entry] = {};
      structure = structure[entry];
    end
    arguments_count = arguments_count - 1;
  end);
end


function expand_variable(variable_path, variable_sets)
  for index=1, #variable_sets do
    local result = try(variable_sets[index], variable_path);
    if result then
      return result;
    end
  end
end

-- replace variables in a string by array values
function expand_variables(line, ...)
  local variable_sets = {...};
  return (line:gsub('{([%a%d%._]+)}', function(captured)
    return expand_variable(captured, variable_sets);
  end))
end


-- concatenate array values
function to_s(array, separator, prefix, suffix)
  require 'common.str';

  local buffer = '';
  for key, value in pairs(array) do
    buffer = common.str.append(buffer, value, separator, prefix, suffix);
  end

  return buffer;
end

-- concatenate array keys
function keys_to_s(array, separator, prefix, suffix)
  require 'common.str';

  local buffer = '';
  for key, value in pairs(array) do
    buffer = common.str.append(buffer, key, separator, prefix, suffix);
  end

  return buffer;
end