diff --git a/src/lua.c b/src/lua.c index 1d4db3b10257..b8e2ca8eccc4 100644 --- a/src/lua.c +++ b/src/lua.c @@ -6,6 +6,7 @@ #include lua_State *luaState; +redisClient *fakeClient; static void *luaZalloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; @@ -26,12 +27,18 @@ static int luaPanic (lua_State *L) { } void initLua(void) { + fakeClient = zmalloc(sizeof(redisClient)); + selectDb(fakeClient, 0); + luaState = lua_newstate(luaZalloc, NULL); if (!luaState) { redisPanic("Unable to initialize Lua!"); } lua_atpanic(luaState, &luaPanic); luaL_openlibs(luaState); + + lua_pushcfunction(luaState, luaExecRedisCommand); + lua_setglobal(luaState, "redis"); } void luaexecCommand(redisClient *c) { @@ -72,3 +79,25 @@ void luaGenericExecCommand(redisClient *c, const char *code) { return; } } + +int luaExecRedisCommand(lua_State *L) { + int nargs = lua_gettop(L); + const char *cmdname = lua_tostring(L, 1); + + struct redisCommand *cmd = lookupCommandByCString(cmdname); + if (nargs != cmd->arity) { + lua_pushstring(L, "incorrect number of arguments"); + lua_error(L); + } + fakeClient->argc = nargs; + fakeClient->argv = zmalloc(sizeof(robj) * nargs); + for (int i = 0; i < nargs; i++) { + char *param = lua_tostring(L, i + 1); + fakeClient->argv[i] = createStringObject(param, strlen(param)); + } + + call(fakeClient, cmd); + + return 0; +} + diff --git a/src/lua.h b/src/lua.h index 24c94b4a4e54..ccecfbe62b2b 100644 --- a/src/lua.h +++ b/src/lua.h @@ -1,9 +1,11 @@ #ifndef __LUA_H #define __LUA_H +#include #include "redis.h" void initLua(void); void luaGenericExecCommand(redisClient *c, const char *); +int luaExecRedisCommand(lua_State *L); #endif