0

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)
Community
  • 1
  • 1
Nicholas Rubin
  • 317
  • 1
  • 4
  • 14

1 Answers1

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.

bpgergo
  • 15,669
  • 5
  • 44
  • 68
  • The 'return w' is in the for loop, no? – Nicholas Rubin Jul 31 '12 at 17:12
  • `return` statement should come after the loop, see the explanation I added to the answer – bpgergo Jul 31 '12 at 17:28
  • Thank you for the explanation. I put a few print statements, and it is printing what I want. 'WC' prints out, "T TO OB BE EO OR RN NO OT TO OB BE EO OR RN NO OT T". Now that I have this, what should be returned? – Nicholas Rubin Jul 31 '12 at 17:40
  • if `print(w)` prints `TOBEORNOTTOBEORNOT` at the end of the last iteration, then do `return w` after the loop. – bpgergo Jul 31 '12 at 17:45
  • Putting print(w) inside of the for loop, after the if statement ends - prints "TOBEORNOTTOBEORNOT nil" (each letter on separate line). If I put return w in the same place as the print(w), after the if statements ends inside of the for loop, it only prints "T". Putting the return w outside/after the for loop prints the same "T". – Nicholas Rubin Jul 31 '12 at 17:51
  • Do I want an answer like this? Returning dictionary inside the for loop returns this 'table: 0x7866c310' – Nicholas Rubin Jul 31 '12 at 18:06