问题描述
这里是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!
推荐答案
假设未压缩
需要使用这样的东西来迭代它:
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
.
您还可以阅读关于字符串连接的性能。很长的故事,通常更有效地保持每个元素在一个表中,并返回它 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()
.
这篇关于LZW压缩在Lua的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!