Pwrcdr87
Pwrcdr87

Reputation: 965

Trying to Check My Work but How to Print()?

I am trying to practice table.sorting and tables in general. I am taking the table t{} below and table.sort it by the numerical value of each of the names. I am having problems printing up the original table t{} once it has been sorted into a{} (I am trying to print a{} just to clear that up). Where would I place the print (and what code?) into code like this?

Sorry for the rookie, beginner question. But I'm having a problem understanding where to stick the print() lines into function or code to check them. I am changing return with print, etc. I still can't grasp this part.

I appreciate the help guys!

 t = {
    Steve = 4,
    Derek = 1,
    Mike = 3,
    Steph = 8,
    Mary = 15,
    Danny = 10
    }

 function pairsByKeys (t,f) 
    local a = {}

    for x in pairs (t) do
        a[#a + 1] = x
    end

    table.sort(a,f)
    local i = 0
    return function ()
    i = i + 1
    return a[i], t[a[i]]
    end
end

local timer = os.time()
repeat until os.time() > timer + 10

Upvotes: 3

Views: 44

Answers (1)

Yu Hao
Yu Hao

Reputation: 122363

pairsByKeys is implemented as an iterator function (like pairs or ipairs provided by the standard library), so you can use it in a generic for statement like this (using the default compare function):

for k,v in pairsByKeys(t) do
    print(k, v)
end

Output:

Danny   10
Derek   1
Mary    15
Mike    3
Steph   8
Steve   4

Upvotes: 2

Related Questions