Skip to content

Instantly share code, notes, and snippets.

@azyu
Created June 15, 2014 04:27
Show Gist options
  • Save azyu/d4e0feda04ddbe2d9f45 to your computer and use it in GitHub Desktop.
Save azyu/d4e0feda04ddbe2d9f45 to your computer and use it in GitHub Desktop.
lua_tinker call with variadic templates (Visual Studio 2013)
#if _MSC_VER >= 1800
template<typename T, typename ... TArgs>
void push(lua_State *L, T ret, const TArgs& ... args) { push(L, ret); push(L, args...); }
template<typename RVal, typename ... TArgs>
RVal call(lua_State* L, const char* name, const TArgs&... args)
{
lua_pushcclosure(L, on_error, 0);
int errfunc = lua_gettop(L);
lua_getglobal(L, name);
if (lua_isfunction(L, -1))
{
push(L, args...);
if (lua_pcall(L, sizeof...(args), 1, errfunc) != 0)
{
lua_pop(L, 1);
}
}
else
{
print_error(L, "lua_tinker::call() attempt to call global `%s' (not a function)", name);
}
lua_remove(L, -2);
return pop<RVal>(L);
}
#endif
@azyu
Copy link
Author

azyu commented Jun 15, 2014

Lua

function lua_func(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12)
  return arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12
end

C++

int result = lua_tinker::call<int>(L, "lua_func", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

Result is 78.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment