0

可能的重复:
Lua 中的 LZW 压缩

这是我在 Lua 中使用 LZW 压缩方法压缩数据的代码。我的问题是该函数返回字符“T”,而不是返回完整的压缩字符串“TOBEORNOTTOBEORNOT”。谢谢!

 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)
4

1 回答 1

1

只是一个提示:你return w在 for 循环中

编辑一些解释

如果您在循环中返回结果,则循环将只进行一次迭代。在第一次迭代结束时,您的函数将完成。这是没有意义的。所以你的 return 语句应该在 for 循环之后。

此外,您声明一个变量result = {}然后从不使用它是可疑的。

因此,我建议您将 return 语句放在循环之后,并在每次迭代结束时打印变量的值(您将 print 语句放在return现在的位置),这样您就可以看到实际发生了什么。

于 2012-07-31T17:07:26.123 回答