Skip to content

Instantly share code, notes, and snippets.

@zah
Created August 30, 2011 08:26
Show Gist options
  • Save zah/1180457 to your computer and use it in GitHub Desktop.
Save zah/1180457 to your computer and use it in GitHub Desktop.
How to get side effects from template instantiations
# First, we introduce advices that modify existing methods:
before foo(b: string): int =
b = "input parameters could be modified" & b
after foo(b: string): int =
result = result & "results too"
wrap foo(b: string): int =
# here, we can write arbitrary code
if flipCoin():
log "entering foo"
foo(b)
log "leaving foo"
# more advanced version (only for future directions):
# matching a set of overloads using generics
before foo[T](a: T) =
# matching any of the foo overloads (uses the same syntax as the tuple varargs
# functions that could be introduced in the future)
before foo(args: varargs) =
# a single rule for multiple functions (mimics an import statement)
before moduleX.{foo|bar|baz*}(args: varargs) =
# Once, we have these, it's a simple matter of marrying them
# to the generic instantiation process.
# We add a rule that advices could be written within procs
# and in the case of a generic proc, the advice will be applied once per instantiation
# This is a heavy operation and we want to perform it just once
proc registerTypeInLua[T]() = ...
# Here is the trick, we create an empty function right now, that
# we'll use as a "bin" where we'll add code later
proc registerAllTypesInLua = nil
# All we need to do is this
proc useInLua[T](t: T) =
after registerAllTypesInLua =
registerTypeInLua[T]()
# normal code of the proc here
var mt = findMetatable[T]
push mt
push t
# now, what's left is just to call our 'bin' function in
# some init procedure to register all types
proc initLuaBind =
var ls = luaNewState()
loadlibs ls
...
registerAllTypesInLua(ls)
# other pattern that we'll probably see often is advices directly to main
before main =
initSomeGlobalContants()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment