Search code examples
arrayssortinglualua-table

How can I return a sorted table index as a string?


I'm very unfamiliar working with LUA and LUA tables.

The example I would like to provide is that I want to know the name of the person who has the least amount of money in his/her bank account:

BankAccount = {}
BankAccount["Tom"] = 432
BankAccount["Henry"] = 55
BankAccount["Kath"] = 875

table.sort(BankAccount)
print("BankAccount Element at index 1 is ", BankAccount[1])

Goal: I would like for it to return the string "Henry".

The problem I'm having is that I'm not sure how to structure the table in such a way for it to return the string based on a value. I've also seen people do:

BankAccount = {
    {"Tom", 432},
    {"Henry", 55},
    {"Kath", 875},
}

So I'm not exactly sure how to proceed. Thank you for your help.


Solution

  • You can't sort the first table, as it's a hash table that doesn't have any specific order, but you can sort the second one if you provide a sorting function:

    BankAccount = {
        {"Tom", 432},
        {"Henry", 55},
        {"Kath", 875},
    }
    table.sort(BankAccount, function(a, b) return a[2] < b[2] end)
    print(BankAccount[1][1]) -- should print Henry
    

    table.sort takes a function as the second parameter that will receive two values being sorted and needs to return true/false value indicating if the first element needs to go before the second (see table.sort).