From 47c81f36eb4205339576b48a2ab8def6f28c2522 Mon Sep 17 00:00:00 2001 From: ElPumpo Date: Wed, 1 May 2019 21:56:49 +0200 Subject: [PATCH] Implemented ESX.Table.Sort() for pairs --- common/modules/table.lua | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/common/modules/table.lua b/common/modules/table.lua index fb862439..ea7dad28 100644 --- a/common/modules/table.lua +++ b/common/modules/table.lua @@ -125,4 +125,35 @@ function ESX.Table.Join(t, sep) end return str +end + +-- Credit: https://stackoverflow.com/a/15706820 +-- Description: sort function for pairs +function ESX.Table.Sort(t, order) + -- collect the keys + local keys = {} + + for k,_ in pairs(t) do + keys[#keys + 1] = k + end + + -- if order function given, sort by it by passing the table and keys a, b, + -- otherwise just sort the keys + if order then + table.sort(keys, function(a,b) + return order(t, a, b) + end) + else + table.sort(keys) + end + + -- return the iterator function + local i = 0 + + return function() + i = i + 1 + if keys[i] then + return keys[i], t[keys[i]] + end + end end \ No newline at end of file