LZW Data Compression In Lua [duplicate]

Deadly 提交于 2019-12-08 13:43:18

问题


Possible Duplicate:
LZW Compression In Lua

Here is my code for compressing data in Lua using the LZW compression method. My problem is that the function is returning the character 'T', instead of returning the full compressed string 'TOBEORNOTTOBEORNOT'. Thanks!

 function compress(uncompressed)
 local dict_size = 256
 local dictionary = {}
   w = ""
   result = {}
     for i = 1, #uncompressed do
       local c = string.sub(uncompressed, i, i)
       local wc = w .. c
       if dictionary[wc] == true then
           w = wc
       else
           dictionary[w] = ""
           dictionary[wc] = dict_size
           dict_size = dict_size + 1
           w = c
       end
     if w then
       dictionary[w] = ""
     end
     return w
   end
 end

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

回答1:


Just a hint: you return w in the for loop

EDIT some explanation

If you return your result in the loop, then the loop will do only one iteration. At the end of the first iteration, your function will finish. That makes no sense. So your return statement should come after the for loop.

Also, it is suspicious that you declare a variable result = {} and then you never use it.

So I suggest you put your return statement after the loop and you print the value of your variables at the end of in each iteration (you'd put the print statements where you have the return now), so you can see what is really happening.



来源:https://stackoverflow.com/questions/11745265/lzw-data-compression-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!