简单的LZW压缩不起作用

时间:2016-05-10 05:47:37

标签: lua compression lzw

我编写了简单的类来压缩数据。这是:

LZWCompressor = {}
function LZWCompressor.new()
  local self = {}
  self.mDictionary = {}
  self.mDictionaryLen = 0
  -- ...
  self.Encode = function(sInput)
    self:InitDictionary(true)
    local s = ""
    local ch = ""
    local len = string.len(sInput)
    local result = {}   
    local dic = self.mDictionary
    local temp = 0
    for i = 1, len do
        ch = string.sub(sInput, i, i)
        temp = s..ch
        if dic[temp] then
            s = temp
        else
            result[#result + 1] = dic[s]
            self.mDictionaryLen = self.mDictionaryLen + 1   
            dic[temp] = self.mDictionaryLen         
            s = ch
        end
    end
    result[#result + 1] = dic[s]
    return result
  end
  -- ...
  return self
end

我按照以下方式运行:

local compressor = LZWCompression.new()
local encodedData = compressor:Encode("I like LZW, but it doesnt want to compress this text.")


print("Input length:",string.len(originalString))
print("Output length:",#encodedData)


local decodedString = compressor:Decode(encodedData)
print(decodedString)
print(originalString == decodedString)

但是当我最终用lua运行它时,它会显示解释器预期的字符串,而不是。这很奇怪,因为我传递了字符串类型的参数。为了测试Lua的日志,我在函数的开头写道:

print(typeof(sInput))

我得到了输出"表"和lua的错误。那么如何解决呢?为什么lua显示那个字符串(我已经通过)是一个表?我使用Lua 5.3。

2 个答案:

答案 0 :(得分:1)

问题在于方法Encode()的定义,并且很可能Decode()具有相同的问题 您可以使用点语法创建Encode()方法:self.Encode = function(sInput)
但是你用冒号语法调用它:compressor:Encode(data)
当您使用冒号语法调用Encode()时,其第一个隐式参数将是compressor本身(来自您的错误的表),而不是数据。
要修复它,请使用冒号语法function self:Encode(sInput)声明Encode()方法,或者将'self'作为第一个参数显式添加self.Encode = function(self, sInput)

答案 1 :(得分:1)

您提供的代码根本不应运行。

您定义function LZWCompressor.new(),但请致电CLZWCompression.new()

在编码内部,您调用尚未定义的self:InitDictionary(true)

也许您没有在此处粘贴所有相关代码。

您遇到错误的原因是您拨打的compressor:Encode(sInput)相当于compressor.Encode(self, sInput)。 (语法糖)由于函数参数不是通过名称传递,而是通过它们在Encode中的位置sInput现在是compressor,而不是你的字符串。 然后将您的第一个参数(恰好是self,一个表)传递给期望字符串的string.len。 因此,您实际上会致电string.len(compressor),这当然会导致错误。

请确保您知道如何调用和定义函数以及如何正确使用自我!