繁体   English   中英

lua尝试调用方法'len'(零值)

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

在我的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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