Lua中的LZW压缩 [英] LZW Compression In Lua

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

问题描述

这是 Lempel-Ziv-Welch 压缩的伪代码.

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

我正在尝试在 Lua 中对此进行编码,但它并没有真正起作用.这是我在 Python 中的 LZW 函数之后建模的代码,但我在第 8 行收到尝试调用字符串值"错误.

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)

我真的很想得到一些帮助,要么让我的代码运行,要么帮助我在 Lua 中编写 LZW 压缩.非常感谢!

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!

推荐答案

假设 uncompressed 是一个字符串,你需要使用这样的东西来迭代它:

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   

第 10 行还有一个问题;.. 在 Lua 中用于字符串连接,所以这一行应该是 local wc = w .. c.

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

关于字符串连接的性能,您可能还想阅读this.长话短说,将每个元素保存在表中并使用 table.concat() 返回它通常更有效.

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().

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

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