diff --git a/ngcp/avp.lua b/ngcp/avp.lua index f8952b9..0cba854 100644 --- a/ngcp/avp.lua +++ b/ngcp/avp.lua @@ -32,6 +32,11 @@ NGCPAvp_MT = { --print(table.tostring(sr.pv.vars)) --print(t.id) return sr.pv.get(t.id) + elseif type(value) == "table" then + local i, v + for i = #value, 1, -1 do + t(value[i]) + end elseif type(value) == "number" then sr.pv.seti(t.id, value) elseif type(value) == "string" then diff --git a/ngcp/utils.lua b/ngcp/utils.lua index 1333e2c..e7dad5a 100644 --- a/ngcp/utils.lua +++ b/ngcp/utils.lua @@ -19,6 +19,25 @@ -- -- Lua utils +-- improving the built-in pseudorandom generator +-- http://lua-users.org/wiki/MathLibraryTutorial +do + local oldrandom = math.random + local randomtable + math.random = function () + if randomtable == nil then + randomtable = {} + for i = 1, 97 do + randomtable[i] = oldrandom() + end + end + local x = oldrandom() + local i = 1 + math.floor(97*x) + x, randomtable[i] = randomtable[i], x + return x + end +end + -- copy a table function table.deepcopy(object) local lookup_table = {} @@ -92,6 +111,15 @@ function table.tostring( tbl ) return "{" .. table.concat( result, "," ) .. "}" end +function table.shuffle(tab) + local n, order, res = #tab, {}, {} + math.randomseed( os.time() ); + for i=1,n do order[i] = { rnd = math.random(), idx = i } end + table.sort(order, function(a,b) return a.rnd < b.rnd end) + for i=1,n do res[i] = tab[order[i].idx] end + return res +end + -- from table to string -- t = {'a','b'} -- implode(",",t,"'") diff --git a/tests/ngcp_avp.lua b/tests/ngcp_avp.lua index ee53e9a..1eef410 100644 --- a/tests/ngcp_avp.lua +++ b/tests/ngcp_avp.lua @@ -66,6 +66,16 @@ TestNGCPAvp = {} --class assertEquals(self.avp:all(), okvals) end + function TestNGCPAvp:test_avp_set_list() + local vals = {1,2, {"3", 4}} + local okvals = {4, "3", 2, 1} + + for i=1,#vals do + self.avp(vals[i]) + end + assertItemsEquals(self.avp:all(), okvals) + end + function TestNGCPAvp:test_clean() self.avp(1) self.avp:clean() diff --git a/tests/utils.lua b/tests/utils.lua index 98cd463..e2cde01 100644 --- a/tests/utils.lua +++ b/tests/utils.lua @@ -58,6 +58,21 @@ TestUtils = {} --class assertEquals(self.simple_list, {1,2,3,5,4}) end + function TestUtils:test_table_shuffle() + assertEquals(self.simple_list, {1,2,3}) + table.add(self.simple_list, 4) + table.add(self.simple_list, 5) + table.add(self.simple_list, 6) + local tmp = table.shuffle(self.simple_list) + assertItemsEquals(self.simple_list, tmp) + assertNotEquals(self.simple_list, tmp) + local tmp2 = table.shuffle(self.simple_list) + assertItemsEquals(self.simple_list, tmp2) + --print(table.tostring(tmp)) + --print(table.tostring(tmp2)) + assertNotEquals(tmp2, tmp) + end + function TestUtils:test_table_tostring() assertError(table.tostring,nil) assertEquals(table.tostring(self.simple_list), "{1,2,3}")