4

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.

0

1 Answer 1

4
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.