Lua 写文件输出奇怪字节

在使用 Lua 二进制数据写 BMP 时,调试问题 关于纵横比问题 时,我遇到了一个奇怪的问题,也就是有些字节被引入了。

当我们写入 string.char(10) 时,会出现字节 0x0D0A。

local file = io.open("forbchars.bin","w")

local out = {}
for i=1,255 do
    out[#out+1] = string.char(i)
    out[#out+1] = string.char(255)
end

file:write(table.concat(out))

如果你使用十六进制编辑器检查这个文件,你会看到 0x0D0A 字节,而不是 0x0A (10)。

如何避免这种情况?这是 Lua 的一个 bug 吗?

点赞
用户4237598
用户4237598

使用二进制开关 "wb" 在 Lua 中写入二进制数据:

local file = io.open("forbchars.bin","wb")
local out = {}
for i=1,255 do
    out[#out+1] = string.char(i)
    out[#out+1] = string.char(255)
end
file:write(table.concat(out))
2021-04-07 02:42:24