Skip to content

Instantly share code, notes, and snippets.

@fur-q
Last active October 10, 2017 06:47
Show Gist options
  • Save fur-q/dba51bdff3cbddf8194a to your computer and use it in GitHub Desktop.
Save fur-q/dba51bdff3cbddf8194a to your computer and use it in GitHub Desktop.
C/Lua interop basic example
static int cf_tolua(lua_State *L) {
lua_pushliteral(L, "hello");
return 1;
}
static int cf_fromlua(lua_State *L) {
const char *str = lua_tostring(L, 1); // first argument passed in; second would be at index 2
printf("%s\n", str);
return 0;
}
static const luaL_Reg my_funcs[] = {
{ "tolua", cf_tolua },
{ "fromlua", cf_fromlua },
{ NULL, NULL }
};
// run this before running your scripts
void register_my_funcs(void) {
lua_getglobal(L, "package");
lua_getfield(L, -1, "loaded");
lua_newtable(L);
luaL_register(L, NULL, my_funcs);
lua_setfield(L, -2, "cfuncs");
}
local cfuncs = require "cfuncs"
print(cfuncs.tolua())
-- "hello"
cfuncs.fromlua("hello")
-- "hello" (printed by C! MAGIC)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment