LZW数据压缩在Lua [英] LZW Data Compression In Lua

查看:228
本文介绍了LZW数据压缩在Lua的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

LZW压缩在Lua中


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

 函数compress(未压缩)
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
如果w then
字典[w] =
end
return w
end
end

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


解决方案

只是一个提示:你在for循环中返回w
$ b

EDIT 一些解释



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



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



因此,我建议你在循环后输入return语句,并在每次迭代结束时打印变量的值(你可以把print语句放在你现在有 return ),所以你可以看到真正发生了什么。


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)

解决方案

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.

这篇关于LZW数据压缩在Lua的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆