Sign in to follow this  

How to use table.sort & table.insert

Recommended Posts

table.sort(table [, comp])

A comparison function can be provided to customise the element sorting. The comparison function must return a boolean value specifying whether the first argument should be before the second argument in the sequence. The default behaviour is for the < comparison to be made. For example, the following behaves the same as no function being supplied:

> t = { 3,2,5,1,4 }
> table.sort(t, function(a,b) return a<b end)
> = table.concat(t, ", ")
1, 2, 3, 4, 5        

We can see if we reverse the comparison the sequence order is reversed.

> table.sort(t, function(a,b) return a>b end)
> = table.concat(t, ", ")
5, 4, 3, 2, 1


table.insert(table, [pos,] value)

Insert a given value into a table. If a position is given insert the value before the element currently at that position:

> t = { 1,3,"four" }
> table.insert(t, 2, "two")  -- insert "two" at position before element 2
> = table.concat(t, ", ")
1, two, 3, four



Edited by Mr.Loki

Share this post

Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.