Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua 简单的LZW压缩不起作用_Lua_Compression_Lzw - Fatal编程技术网

Lua 简单的LZW压缩不起作用

Lua 简单的LZW压缩不起作用,lua,compression,lzw,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 = "" loc

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

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的日志,我在函数beggining中写道:

print(typeof(sInput))

我得到了输出“表”和lua的错误。那么如何修复它呢?为什么lua显示的字符串(我已经传递)是一个表?我使用Lua5.3。

问题在于方法Encode()的定义,而Decode()很可能也有同样的问题。
使用点语法创建Encode()方法:
self.Encode=function(sInput)

但是你用冒号语法调用它:
compressor:Encode(data)

使用冒号语法调用Encode()时,它的第一个隐式参数将是
压缩器
本身(错误中的表),而不是数据。

若要修复此问题,请使用冒号语法声明Encode()方法:
函数self:Encode(sInput)
,或将“self”作为第一个参数显式添加
self.Encode=function(self,sInput)
您提供的代码不应运行

您定义了
函数LZWCompressor.new()
,但调用了
CLZWCompression.new()

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

可能您没有将所有相关代码粘贴到此处

出现错误的原因是调用了
compressor:Encode(sInput)
,这相当于
compressor.Encode(self,sInput)
。(语法糖)由于函数参数不是通过名称传递的,而是通过它们的位置传递的,因此编码现在是压缩程序,而不是字符串。 然后,您的第一个参数(恰好是
self
,一个表)被传递到
string.len,它需要一个字符串。
因此,您实际调用了
string.len(compressor)
,这当然会导致错误


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

下次请你自己多努力解决这个问题。“为什么这个代码不起作用”的问题往往会被否决或删除。此外,我不能简单地运行您的代码来查看发生了什么,因为您没有提供正确的解决方案。请阅读我已将呼叫中的CLZWCompression更改为LZWCompression。