Skip to content

Instantly share code, notes, and snippets.

@zah
Created August 29, 2011 18:23
Show Gist options
  • Save zah/1179016 to your computer and use it in GitHub Desktop.
Save zah/1179016 to your computer and use it in GitHub Desktop.
Typesafe variadics hack
# Some generic functions that convert nimrod values to lua
proc push(ls: PState, s: string) = pushstring(ls, s)
proc push(ls: PState, i: int) = pushinteger(ls, i)
proc push(ls: PState, f: float) = pushnumber(ls, f)
# helpers for creating type safe variadic functions
proc argsToTuple(expr: PNimrodNode) : PNimrodNode {.compileTime.} =
result = newNimNode(nnkPar)
for i in 1..expr.len-1: add(result, expr[i])
template vararg_proc(name: expr, returnType: typeDesc, body: stmt) : stmt =
proc `name NM_IMPL` [T](args : T) : returnType =
body
macro name (args: expr) : expr =
var impl = toStrLit(args[0]).strVal & "NM_IMPL"
result = newCall(!impl, argsToTuple(args))
# example generic function to perform arbitrary lua call
vararg_proc luaCall, int:
var ls = args[0]
# hack to deal with the limitation that we can't unroll on a subset of the tuple fields
proc push(ls: PState, ls2: Pstate) {.inline.} = nil
for field in fields(args):
push ls, field
call(l, len(args) - 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment