Skip to content

Instantly share code, notes, and snippets.

@JakSprats
Created November 2, 2010 14:00
Show Gist options
  • Save JakSprats/659636 to your computer and use it in GitHub Desktop.
Save JakSprats/659636 to your computer and use it in GitHub Desktop.
compile_lua_redis.sh
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "math.h"
int myCfunc(lua_State *L) {
printf (" START running C redis (LUA)\n");
double d = lua_tonumber(L, 1);
lua_pushnumber(L, d * d);
printf (" END running C redis (LUA)\n");
return 1;
}
int main() {
lua_State *L = lua_open();
luaL_openlibs(L);
lua_register(L, "redis", myCfunc);
if (luaL_loadfile(L, "ccall.lua") || lua_pcall(L, 0, 0, 0)) {
printf("0: error: %s", lua_tostring(L, -1));
return -1;
}
lua_getglobal(L, "squarer");
if(!lua_isfunction(L, -1)) {
printf("function not found\n");
lua_pop(L,1);
return -1;
}
lua_pushnumber(L, 12); /* push 1st argument */
/* do the call (2 arguments, 1 result) */
printf("START: calling from C main()\n");
if (lua_pcall(L, 1, 1, 0) != 0) {
printf("error running function `f': %s\n",lua_tostring(L, -1));
return -1;
}
printf("END: calling from C main()\n");
/* retrieve result */
if (!lua_isnumber(L, -1)) {
printf("function `redis' must return a number\n");
return -1;
}
double z = lua_tonumber(L, -1);
printf("Result: %f\n",z);
lua_pop(L, 1);
lua_close(L);
return 0;
}
function squarer(x)
io.write(" lua level -> START call C\n");
sum = redis(x);
io.write(" lua level -> END call C\n");
return sum;
end
START: calling from C main()
lua level -> START call C
START running C redis (LUA)
END running C redis (LUA)
lua level -> END call C
END: calling from C main()
Result: 144.000000
#!/bin/bash
echo gcc -I/usr/include/lua5.1/ -L/usr/local/lib/ -llua -o call_lua{,.c} -llua -ldl -lm
gcc -I/usr/include/lua5.1/ -L/usr/local/lib/ -llua -o call_lua{,.c} -llua -ldl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment