lua-users home
lua-l archive

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


Thinking ahead about some conventions related to scoped variables:

Libraries and classes will have functions intended for use with scoped vars.  They will acquire some resource or otherwise initialize state, returning an exit function.

It would be good to have a naming convention from the onset, so it's clear when an API is meant for scoped vars.  Perhaps the prefix "scoped".

   local scoped _ = my_lock:scoped_acquire()

or if the semantics are obvious, simply:

   local scoped _ = my_lock:scoped()

There is the question about how to represent errors in acquiring the resource.  In this example it's an error if the lock is already active.  It's strongly preferred to use exceptions for errors.  Given that scoped vars are tied to exception safety, it's reasonable to assume exceptions will be acceptable to users of the library.

The alternative of returning "nil, error" is problematic:

  local scoped l, err = my_lock:scoped()

The issues being that 1) it's wasteful to used a scoped var for err, 2) if err happened to be a callable then unexpected behavior would ensue.  #2 could be due to some lower level dependency out of the library author's control.