在我的 lua 项目中,我得到了以下功能:
function module.Cp1251ToUtf8(s)
if s == nil then return nil end
local r, b = ''
for i = 1, s and s:len() or 0 do --the problem occurs here
b = s:byte(i)
if b < 128 then
r = r..string.char(b)
else
if b > 239 then
r = r..'\209'..string.char(b - 112)
elseif b > 191 then
r = r..'\208'..string.char(b - 48)
elseif cp1251_decode[b] then
r = r..cp1251_decode[b]
else
r = r..'_'
end
end
end
return r
end
所以据我所知,这个函数获取一个字符串并转换它的编码。有时它工作正常,但有时我会收到以下错误:
attempt to call method 'len' (a nil value)
。任何想法会是什么以及如何解决它?我试图删除
s:len()
或插入类似 if s != nil then ...
的条件,但它也不起作用。 最佳答案
if s == nil then return nil end
以上拒绝零值。但是还有其他非字符串,因此请收紧检查:
if type(s) ~= 'string' return nil end
关于lua 尝试调用方法 'len'(一个 nil 值),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55856614/