2012-07-31 139 views
1

這是Lempel-Ziv-Welch壓縮的僞代碼。LZW在Lua中的壓縮

pattern = get input character 
while (not end-of-file) { 
    K = get input character 
    if (<<pattern, K>> is NOT in 
      the string table){ 
     output the code for pattern 
     add <<pattern, K>> to the string table 
     pattern = K 
    } 
    else { pattern = <<pattern, K>> } 
} 
output the code for pattern 
output EOF_CODE 

我想在Lua中對此進行編碼,但實際上並不奏效。下面是我在Python的LZW功能仿照代碼,但我得到一個「試圖調用一個字符串值」錯誤在線8.

function compress(uncompressed) 

local dict_size = 256 
local dictionary = {} 

w = "" 
result = {} 
for c in uncompressed do 
    -- while c is in the function compress 
    local wc = w + c 
    if dictionary[wc] == true then 
     w = wc 
    else 
     dictionary[w] = "" 
     -- Add wc to the dictionary. 
     dictionary[wc] = dict_size 
     dict_size = dict_size + 1 
     w = c 
    end 
-- Output the code for w. 
if w then 
    dictionary[w] = "" 
end 
end 
return dictionary 
end 

compressed = compress('TOBEORNOTTOBEORTOBEORNOT') 
print (compressed) 

我真的很喜歡一些幫助或者讓我的代碼運行,或者幫助我在Lua中編碼LZW壓縮。非常感謝!

+0

可能重複:[LZW數據壓縮在Lua中(http://stackoverflow.com/ q/11745265) – 2012-07-31 17:33:14

+0

[LZW數據壓縮在Lua]中可能的重複(http://stackoverflow.com/questions/11745265/lzw-data-compression-in-lua) – JosephH 2012-07-31 19:19:56

回答

2

假設uncompressed是一個字符串,你需要使用這樣的事情來遍歷它:

for i = 1, #uncompressed do 
    local c = string.sub(uncompressed, i, i) 
    -- etc 
end 

有10號線的另一個問題;用於Lua中的字符串連接,所以該行應該是local wc = w .. c

您可能還希望閱讀this關於字符串連接的性能。長話短說,將每個元素保存在一張表格中並以table.concat()的形式返回它往往更有效率。

+1

對不起,我對此很新。 。但是--etc評論後應該怎麼辦?非常感謝! – 2012-07-31 16:32:03

+0

你已經在你的循環中的代碼:) – furq 2012-07-31 16:32:52

+0

它沒有錯誤地運行!謝謝!我現在的小問題是它正在打印「表格:0x7861e7f0」......謝謝! – 2012-07-31 16:34:40

2

你也應該看看here下載源在Lua高性能LZW壓縮算法...

+0

謝謝你,但我想自己編碼。 – 2012-07-31 17:41:30

+0

啊,但它顯示了一些不錯的Lua技術可能有用。 – mackworth 2012-07-31 18:36:22

+0

另請注意,其許可證是GPL版本2 – Perry 2014-02-01 00:00:32