调用函数在Lua中作为参数传递

时间:2013-02-27 03:05:55

标签: functional-programming lua

我有这段代码

Option = { }


function Option.nothing( )
  local self = { isNone = true, isSome = false }

  function self:orElse( alt )
    return alt
  end

  function self:map( f )
    return Option.nothing( )
  end

  function self:exec( f )
  end

  function self:maybe( alt, f )
    return alt
  end

  return self
end



function Option.just( val )
  local self = { isNone = false, isSome = true }
  local value = val

  function self:orElse( alt )
    return value
  end

  function self:map( f )
    return Option.just( f(value) )
  end

  function self:exec( f )
    f( value )
  end

  function self:maybe( alt, f )
    return f(value)
  end

  return self
end



function printOpt( opt )
  local str = opt.maybe( "Nothing", function(s) return "Just " .. s end )
  print( str )
end


x = Option.nothing( )
y = Option.just( 4 )

printOpt(x)
printOpt(y)

但我一直试图'尝试在这里调用本地'f'(零值):

  function self:maybe( alt, f )
    return f(value)
  end

看来我在调用作为参数传递的函数时遇到了麻烦。

1 个答案:

答案 0 :(得分:6)

您将该函数声明为self:maybe(),但您将其称为opt.maybe()。您应将其称为opt:maybe()

将其声明为self:maybe(alt, f)相当于将其声明为self.maybe(self, alt, f)。因此,如果您使用.调用它,则需要3个参数。您传递了2,因此self最终为"Nothing"alt最终作为函数对象。

但是,通过将其称为opt:maybe("Nothing", f),这相当于说opt.maybe(opt, "Nothing", f),它提供了所需的3个参数。