簡體   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