"尝试呼叫表"没有

时间:2018-03-01 19:32:50

标签: oop lua lua-table

当我调用我创建的方法流时,以任何表作为参数,我得到错误"尝试调用表"。

据我所知,只有当我使用错误时才会出现此错误,但我在执行的代码中没有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

Full Source - Older Version(由于某种原因,参数被删除)

我想将该方法用于更基于流的编程风格。 与this项目非常相似,但不仅仅是数字和命名键。

1 个答案:

答案 0 :(得分:0)

在您的代码中

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())