Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Best way to order values in size?

Asked by
Mystdar 352 Moderation Voter
9 years ago

If I had 8 values is there a way I can easily order them in size order, without lots of lines of code? Example with 3 values

Values = [1, 2, 3]
For i in Values do
    if Values[1]  > Values[2] > Values[3] then
        print (Values[1].." is bigger than "..Values[2].." which is bigger than "..Values[3])
    if Values[2] > Values[3] > Values[1] then
        print (Values[2].." is bigger than "..Values[3].." which is bigger than "..Values[1])
     -- etc

As you can see this is inefficient, is there a more efficient way, considering I require 8 values

1 answer

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
9 years ago

The best, most efficient way to do this would be using the table.sort function.

So, you have a table full of numbers and you want to sort them from least to greatest?

local values = {5,3,7,2,1,8}

table.sort(values) --Sort them

print(table.concat(values," ")) --Print the whole table, with a space between each index.

This code would print; 1 2 3 5 7 8



--EDIT--

table.concat is a method that takes 2 arguments. The first argument should be the table, and the the second should be the intersection between each index of the table.

Example;

local tab = {"I","Really","Like","Roblox"}
local sentence = table.concat(tab," ")
--[[First argument is the table, 'tab'. The second is what goes in between each index, " ", or a space.]]
print(sentence) --> I Really Like Roblox

--[[Alternatively, if I were to make the second argument ", " then it would put a comma in between each index.]]

local sentence = table.concat(tab,", ")
print(sentence) --> I, Really, Like, Roblox

More info about table.concat here.

Also, you can use the unpack function.

0
Thanks, I read up on concat and struggled to understand it can you breifly explain it please? (the concat argument of a table) Mystdar 352 — 9y
0
I edited. Goulstem 8144 — 9y
Ad

Answer this question