Reputation: 857
in my lua project I got the following function:
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
So as far as I understand this function gets a string and converts its encoding. Sometimes it works fine, but sometimes I get the following error: attempt to call method 'len' (a nil value)
. Any ideas what would it be and how to fix it?
I tried to remove s:len()
or insert a condition like if s != nil then ...
but it also did not work.
Upvotes: 4
Views: 1495
Reputation: 45654
if s == nil then return nil end
The above rejects nil-values. But there are other non-strings, so tighten your check:
if type(s) ~= 'string' return nil end
Upvotes: 4