2

I have this code

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)

But I keep getting 'attempt to call local 'f' (a nil value)' here:

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

It seems I'm having trouble calling a function passed as a argument.

1 Answer 1

6

You declared the function as self:maybe(), but you're calling it as opt.maybe(). You should call it as opt:maybe().

Declaring it as self:maybe(alt, f) is equivalent to declaring it as self.maybe(self, alt, f). So if you call it with a . you need 3 args. You're passing 2, so self ends up as "Nothing", and alt ends up as the function object.

However, by calling it as opt:maybe("Nothing", f) this is equivalent to saying opt.maybe(opt, "Nothing", f) which provides the required 3 args.

Sign up to request clarification or add additional context in comments.

2 Comments

Mike, if you're going to edit my code, please make sure you're actually correct. The first arg to maybe(), i.e. self, does indeed get the value "Nothing". It does not get nil.
In case you're confused, the one call to opt.maybe() in the OP's source calls it as opt.maybe("Nothing", function(s)...end)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.