简体   繁体   中英

lua attempt to call method 'len' (a nil value)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM