lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2009/1/26 Sam Roberts <vieuxtech@gmail.com>:
> On Mon, Jan 26, 2009 at 12:17 PM, Mark Tomczak <mtomczak@wildpockets.com> wrote:
>> Under the present language rules, myInstance:instanceMethod is an error (as
>> I understand it) because the colon notation is only valid in the context of
>> function calls and function declarations, but is not valid in the context of
>> specifying a function value. Currently, we can accomplish this goal by
>> instead making the statement "CallbackManager.postMyCallback(function ()
>> myInstance:instanceMethod() end)", but that seems to be a great deal more
>> typing than should be necessary.
>
> You could also do:
>
> CallbackManager.postMyCallback(myInstance.instanceMethod, myInstance)
>
> Which is only a bit more typing, and follows the common pattern of
> assert() and pcall().
>
> Or you could add a helper function:
>
> CallbackManager.postMyCallback(bind(myInstance, "instanceMethod"))
>
> Where:
> function bind(instance, method)
> return function () return (instance[method])(instance) end
> end
>
> And you can rename bind to something shorter, "B"?, if you are really
> into saving characters.
>
> Or, you can handle it at the other end:

You can do a variant of that without the quotes:

CallbackManager.postMyCallback(wrap(myInstance).instanceMethod)

where:

function wrap(instance)
  return setmetatable({}, {__index=function(_, method)
    return function(...)
      return instance[method])(instance, ...)
    end
  end})
end

This could be a good starting point to implement the colon syntax
extension proposal with a simple token filter.