Last active
October 10, 2017 06:47
-
-
Save fur-q/dba51bdff3cbddf8194a to your computer and use it in GitHub Desktop.
C/Lua interop basic example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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