Need help on improving the efficiency of my code

I’m making a Teddy Bear Simulator game and wanted to know if there is a better way of returning an array sorted based on a predetermined integer

Here is my code:

function sortedBears()

local bears = TeddyBears:GetChildren()
local nums = {}
local sorted = {}

for k in pairs(bears) do
    local bear = ServerStorage.TeddyBears:GetChildren()[k]
    nums[k] = bear.Order.Value
end

table.sort(nums)

for k in pairs(bears) do
    local bear = ServerStorage.TeddyBears:GetChildren()[k]
    for x in pairs(nums) do
        if bear.Order.Value == nums[x] then
            sorted[x] = bear
        end
    end
end

return sorted

end

1 Like

Sure! Assuming by predetermined integer you mean the number specified by bear.Order.Value you could create a sorted list via:

local sortedBears = TeddyBears:GetChildren()
table.sort(sortedBears, function(bear1, bear2) return bear1.Order.Value < bear2.Order.Value end)
-- now sortedBears is sorted!

In this case, index 1 would be the bear with lowest value. Just flip the inequality to reverse the order.

The table.sort function has a second optional parameter allowing you to specify how you’d like the list to be sorted. More information here:
https://developer.roblox.com/en-us/api-reference/lua-docs/table

(Also this is my first reply on the forum yay hope I did good)

2 Likes