Results 1 to 2 of 2

Thread: Print a table in order?

  1. #1

    Print a table in order?

    I have a table that I need to print out in order. I know LUA tables are not ordered.. but I am having a terrible time printing it out in an ordered way. I have cut a dozen code snips the internet and I just can not get it to work.

    Say I have a table like this

    Code:
    local tableofStuff = {}
          tableofStuff['White'] = 15
          tableofStuff['Red'] = 55
          tableofStuff['Orange'] = 5
          tableofStuff['Pink'] = 12
    How can I get it to print like this...

    Red, 55
    White, 15
    Pink, 12
    Orange, 4
    Thanks!
    My Boardgame uTube chan - Tragic's Table Top
    BGG Guild of BoardGame uTubers - Tube Tables

  2. #2
    Join Date
    May 2016
    Posts
    1,072
    As you say, non-numerically indexed tables are not ordered. So you have 2 options.

    Option 1) Make an ordered reference table

    In general, say you always wanted to print Red then White then Pink then Orange. You just make a table {"Red", "White", "Pink", "Orange"} and then loop over that table to get the keys in the order you want, and pull from tableofStuff with the given key. However, it looks like you want to sort by score. In which case, option 2 is more what you need.

    Option 2) Sorting ordered tables

    You keep your data in an ordered table in the first place, or place it into one when it comes time to sort. That would look like this:

    Code:
    scoreList = {
        {color="Red", score=55},
        {you get the idea},
        {you get the idea},
        {you get the idea},
    }
    Then you run a sorting function on it to order the entries.

    Code:
    --Sorts table
    local sort_func = function(a,b) return a["score"] > b["score"] end
    table.sort(scoreList, sort_func)
    And now you have an ordered list that has the entries sorted into the order you desire.

    EXAMPLE: https://ideone.com/ATMaXA

Similar Threads

  1. [SOLVED] Regarding Turn Order
    By Johnnymaxx in forum Scythe
    Replies: 4
    Last Post: 02-07-2017, 11:46 AM
  2. Replies: 2
    Last Post: 09-11-2016, 08:04 AM
  3. Replies: 5
    Last Post: 06-20-2016, 07:02 PM
  4. [ADDED] [v9.4] Custom turn order
    By Wakke in forum Suggestions
    Replies: 1
    Last Post: 02-15-2016, 09:11 PM
  5. A place for all my Print to Play games?
    By justin.veazey in forum General Discussion
    Replies: 3
    Last Post: 03-17-2014, 10:41 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •