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

Help understanding the Table.Sort function?

Asked by
hiccup111 231 Moderation Voter
6 years ago
Edited 6 years ago

Hey guys, could you help me out with a problem?

I'm trying to program the Huffman Encoding algorithm in Lua, and I'm having trouble sorting my tables in order.

Script:

-- Lua version of Huffman Encoding
local buffer = {}       -- This is where the characters of <str> get broken down into 0/1 if statements.
local input = ""

function Enc(s)                 -- <s> for string

    buffer = {}                 -- new buffer (global for decoding)
    local c = {}                -- use to count unique characters in s and how often the occur
    local l = string.len(s)     -- gets the length of the string


    -- This separates all unique characters and counts their occurance in <s>
    for i = 1,l do
        local n = string.sub(s,i,i) -- the Next single character in <s>
        if n then -- Check if the current character has already been added to <c>
            if c[n] then
                c[n] = c[n] + 1
                print("Added character:",n,c[n])
            else
                c[n] = 1
                print("New character:",n)
            end
        end
    end

    print("Bef",table.concat(c," "))
    table.sort(c,function(v0,v1) return c[v0] > c[v1] and v0 or v1 end)
    print("Aft",table.concat(c," "))
end

function Dec(b) -- b for binary

end

Enc("AABBBC")

Just to give you an idea, the huffman process converts text to binary, and builds a hierarchy of the most occurring characters to the least occurring characters.

The Enc function first goes through the string (s) and counts how many times a letter has occurred, writing a table (c) with the Index representing the letter, and value representing the occurrence: c = { "A" = 2; "B" = 3; "C" = 1; }

I want to sort this according to Value - not Index, but I'm struggling how the sort function works, especially since it doesn't allow prints from inside the sort function... =[

Any help with the sort function would be really appreciated.

Answer this question