Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
668 views
in Technique[技术] by (71.8m points)

function - LZW Compression In Lua

Here is the Pseudocode for Lempel-Ziv-Welch Compression.

 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

I am trying to code this in Lua, but it is not really working. Here is the code I modeled after an LZW function in Python, but I am getting an "attempt to call a string value" error on line 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)

I would really like some help either getting my code to run, or helping me code the LZW compression in Lua. Thank you so much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming uncompressed is a string, you'll need to use something like this to iterate over it:

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

There's another issue on line 10; .. is used for string concatenation in Lua, so this line should be local wc = w .. c.

You may also want to read this with regard to the performance of string concatenation. Long story short, it's often more efficient to keep each element in a table and return it with table.concat().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...