array.lua 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. ---@class array
  2. array = {}
  3. function array.clear(t)
  4. local count = #t
  5. for i = 1, count do
  6. table.remove(t)
  7. end
  8. end
  9. function array.length(t)
  10. return t and #t or 0
  11. end
  12. function array.contains(t, item)
  13. return array.indexOf(t, item) ~= nil
  14. end
  15. function array.indexOf(t, item)
  16. for k, v in ipairs(t) do
  17. if v == item then
  18. return k
  19. end
  20. end
  21. return nil
  22. end
  23. function array.random(t)
  24. math.randomseed(os.time())
  25. for i = 1, #t do
  26. local j = math.random(i)
  27. table[i], table[j] = table[j], table[i]
  28. end
  29. end
  30. function array.deepCopy(tableToCopy)
  31. local copy = {}
  32. for key, value in pairs(tableToCopy) do
  33. if type(value) == 'table' then
  34. copy[key] = array.deepCopy(value)
  35. else
  36. copy[key] = value
  37. end
  38. end
  39. return copy
  40. end
  41. -- 去重
  42. function array.removeDup(arr)
  43. local seen = {}
  44. local result = {}
  45. for _, v in ipairs(arr) do
  46. if not seen[v] then
  47. seen[v] = true
  48. table.insert(result, v)
  49. end
  50. end
  51. return result
  52. end
  53. -- 忽略string,number类型的比较
  54. function array.simpleContains(t, item)
  55. local itemStr = tostring(item)
  56. for _, v in ipairs(t) do
  57. local vStr = tostring(v)
  58. if vStr == itemStr then
  59. return true
  60. end
  61. end
  62. return false
  63. end