簡體   English   中英

“嘗試調用表”而沒有 for

[英]"attempt to call table" without for

當我使用任何表作為參數調用我創建的方法流時,我收到錯誤“嘗試調用表”。

據我所知,此錯誤僅在我使用 for 錯誤時發生,但我在執行的代碼中沒有 for ......

function stream(input)
  ...
  local function _stream(input)
    local result = {
      _stream = true,
      _data = input._data or input,
      -- Without the Operation-wrapping no function could access the input
      -- Intermediate Operations
      concat = function(str) return _concat(input,str) end,
      distinct = function(func) return _distinct(input,func) end,
      filter = function(func) return _filter(input,func) end,
      limit = function(n) return _limit(input,n) end,
      map = function(func) return _map(input,func) end,
      skip = function(n) return _skip(input,n) end,
      sort = function(func) return _sort(input,func) end,
      split = function(func) return _split(input,func) end,
      -- Terminal Operations
      allmatch = function(func) return _allmatch(input,func) end,
      anymatch = function(func) return _anymatch(input,func) end,
      collect = function(coll) return _collect(input,coll) end,
      count = function() return _count(input) end,
      foreach = function(func) return _foreach(input,func) end,
      max = function(func) return _max(input,func) end,
      min = function(func) return _min(input,func) end,
      nonematch = function(func) return _nonematch(input,func) end,
      reduce = function(init,op) return _reduce(input,init,op) end,
      toArray = function() return _toArray(input) end
    }
    return result
  end

  if input == nil then
    error("input must be of type table, but was nil")
  elseif type(input) ~= "table" then
    error("input must be of type table, but was a "..type(input)..": "..input)
  end
  return _stream(input)
end

table.stream = stream

完整源-舊版本(由於某種原因參數被刪除)

我想將該方法用於更基於流的編程風格。 這個項目非常相似,但不僅僅是數字和命名鍵。

在你的代碼中

function stream(input)
  -- ...

  local function _count()
    local count = 0
    for k, v in pairs(input._data) do
      count = count + 1
    end
    return count
  end

  -- ...

  local function _stream(input)
    local result = {
      _stream = true,
      _data = input._data or input,
      -- ...
      count = _count,
      -- ...
    }
    return result
  end

  return _stream(input)
end

print(stream({1,2,3}).count())

所創建的對象_stream(input)確實含有_data領域,但input的upvalue仍是指你的論點{1,2,3}不具有_data領域。

它可以通過使用對象而不是輸入參數來修復:

function stream(input)
  -- ...

  local obj

  local function _count()
    local count = 0
    for k, v in pairs(obj._data) do
      count = count + 1
    end
    return count
  end

  -- ...

  local function _stream(input)
    local result = {
      _stream = true,
      _data = input._data or input,
      -- ...
      count = _count,
      -- ...
    }
    return result
  end

  obj = _stream(input)

  return obj
end

print(stream({1,2,3}).count())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM