Lua中涉及字符串比较的奇怪错误。

我正在尝试用Lua创建一个从Web上提取图像的程序。一个小问题是图像有时没有扩展名或扩展名不正确。例如,查看这个动画“jpeg”:http://i.imgur.com/Imvmy6C.jpg

因此,我创建了一个函数来检测图像的文件类型。它非常简单,只需比较返回图像的前几个字符。 Png文件以PNG开头,Gifs以GIF开头,而JPGs以奇怪的符号“╪”开头。

这有点黑客,因为图像不应表示为字符串,但它运行良好。除了实际运行代码时。

当我将代码输入命令行时,它正常工作。但当我运行其中包含代码的文件时,它不起作用。更奇怪的是,它只在jpg上失败。它仍然正确识别PNG和GIF。

以下是重现错误所需的最小代码:

http = require "socket.http"
function detectImageType(image)
    local imageType = "unknown"
    if string.sub(image, 2, 2) == "╪" then imageType = "jpg" end
    return imageType
end
image = http.request("http://i.imgur.com/T4xRtBh.jpg")
print(detectImageType(image))

将其复制并粘贴到命令行中会正确返回“jpg”。将其作为文件运行会返回“unknown”。

我正在使用Lua for Windows软件包中的Lua 5.1.4,通过Windows 8.1上的powershell使用。

编辑:

找到了问题string.byte(“╪”)返回命令行上的216,文件运行时返回226。我不知道为什么,也许是lua和powershell之间的不同编码?

这行代码解决了问题:

if string.byte(string.sub(image, 2, 2)) == 216 then imageType = "jpg" end
点赞
用户1776495
用户1776495

我认为这是因为您保存文件时将其保存为不同的编码,因此╪字符可能被转换为另一个字符。将其转换为字节代码更加健壮:

http = require "socket.http"
function detectImageType(image)
    local imageType = "unknown"
    if string.byte(image, 2) == 216 then imageType = "jpg" end
    return imageType
end
image = http.request("http://i.imgur.com/T4xRtBh.jpg")
print(detectImageType(image))
2014-08-02 22:32:06