1-- 2-- table.lua 3-- Additions to Lua's built-in table functions. 4-- Copyright (c) 2002-2008 Jason Perkins and the Premake project 5-- 6 7 8-- 9-- Returns true if the table contains the specified value. 10-- 11 12 function table.contains(t, value) 13 for _,v in pairs(t) do 14 if (v == value) then 15 return true 16 end 17 end 18 return false 19 end 20 21 22-- 23-- Enumerates an array of objects and returns a new table containing 24-- only the value of one particular field. 25-- 26 27 function table.extract(arr, fname) 28 local result = { } 29 for _,v in ipairs(arr) do 30 table.insert(result, v[fname]) 31 end 32 return result 33 end 34 35 36 37-- 38-- Flattens a hierarchy of tables into a single array containing all 39-- of the values. 40-- 41 42 function table.flatten(arr) 43 local result = { } 44 45 local function flatten(arr) 46 for _, v in ipairs(arr) do 47 if type(v) == "table" then 48 flatten(v) 49 else 50 table.insert(result, v) 51 end 52 end 53 end 54 55 flatten(arr) 56 return result 57 end 58 59 60-- 61-- Merges an array of items into a string. 62-- 63 64 function table.implode(arr, before, after, between) 65 local result = "" 66 for _,v in ipairs(arr) do 67 if (result ~= "" and between) then 68 result = result .. between 69 end 70 result = result .. before .. v .. after 71 end 72 return result 73 end 74 75 76-- 77-- Returns true if the table is empty, and contains no indexed or keyed values. 78-- 79 80 function table.isempty(t) 81 return not next(t) 82 end 83 84 85-- 86-- Adds the values from one array to the end of another and 87-- returns the result. 88-- 89 90 function table.join(...) 91 local result = { } 92 for _,t in ipairs(arg) do 93 if type(t) == "table" then 94 for _,v in ipairs(t) do 95 table.insert(result, v) 96 end 97 else 98 table.insert(result, t) 99 end 100 end 101 return result 102 end 103 104 105-- 106-- Return a list of all keys used in a table. 107-- 108 109 function table.keys(tbl) 110 local keys = {} 111 for k, _ in pairs(tbl) do 112 table.insert(keys, k) 113 end 114 return keys 115 end 116 117 118-- 119-- Translates the values contained in array, using the specified 120-- translation table, and returns the results in a new array. 121-- 122 123 function table.translate(arr, translation) 124 local result = { } 125 for _, value in ipairs(arr) do 126 local tvalue 127 if type(translation) == "function" then 128 tvalue = translation(value) 129 else 130 tvalue = translation[value] 131 end 132 if (tvalue) then 133 table.insert(result, tvalue) 134 end 135 end 136 return result 137 end 138 139