Lua Native Function
Last updated on
Lua is unique, its simple to setup, simple to learn, and simple to bind, most embedable scripting languages fail at least one of these.
I don’t cover building Lua as its trivial, you don’t need any special build flags, if you are on macOS you can use brew.
brew install luaLinux will have similar, Windows errr … yeah anyway.
Call a native function…
/* lua.c */
#include <lua/lua.h>
#include <lua/lualib.h>
#include <lua/lauxlib.h>
#include <stdio.h>
int
native_wrapper(lua_State *L) {
int arg_count = lua_gettop(L);
if(arg_count) {
printf("%s\n", lua_tostring(L, 1));
}
return 0; /* number of returns */
}
void
lua_native_function(lua_State *L) {
const char * script_b = "native_func(\"Lua to Native\")";
lua_register(L, "native_func", native_wrapper);
luaL_dostring(L, script_b);
}
int
main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_native_function(L);
lua_close(L);
return 0;
}Outputs …
Lua to NativeBuild and run …
clang lua.c -I /usr/local/include -L /usr/local/lib -llua && ./a.out