LZW压缩在Lua中

以下是 Lempel-Ziv-Welch 压缩的伪代码。

pattern = 获取输入字符
while (未到文件结尾) {
    K = 获取输入字符
    如果(<<pattern, K>> 不在字符串表中) {
         输出 pattern 的代码
         将 <<pattern, K>> 添加到字符串表中
         pattern = K
    }
    否则 { pattern = <<pattern, K>> }
}
输出 pattern 的代码
输出 EOF_CODE

我试图在 Lua 中编写此代码,但它并没有正常工作。下面是我基于 Python 中的 LZW 函数模拟的代码,但我在第 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 压缩。非常感谢!

点赞
用户1516484
用户1516484

假设uncompressed是一个字符串,你需要使用以下代码来迭代它:

for i = 1, #uncompressed do
  local c = string.sub(uncompressed, i, i)
  -- etc
end

第十行还有一个问题;在Lua中,字符串拼接使用..。因此,这行代码应该是local wc = w .. c

你可能还想阅读这篇文章,关于字符串拼接的性能。长话短说,通常更有效率的做法是将每个元素保留在表中,然后使用table.concat()返回它。

2012-07-31 16:28:33
用户580850
用户580850

你还应该在这里查看:http://www.wowace.com/addons/libcompress/files/39-r49-release-nolib/,以下载用Lua编写的高性能LZW压缩算法的源代码...

2012-07-31 16:48:10