Phil CK

Lua 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 lua

Linux will have similar, Windows errr … yeah anyway.

Call a Lua Function…

/* lua.c */
#include <lua/lua.h>
#include <lua/lualib.h>
#include <lua/lauxlib.h>
#include <stdio.h>


void
lua_call_function(lua_State *L) {
        const char * script_c = "function lua_func(str)\n print(str)\n end";
        luaL_dostring(L, script_c);
        lua_getglobal(L, "lua_func");
        const char *str = "Native to Lua";
        lua_pushstring(L, str);

        int arg_count = 1;
        int ret_count = 0;
        if (lua_pcall(L, arg_count, ret_count, 0) != 0) {
                  printf("err %s\n", lua_tostring(L, -1));
        }

}


int
main() {
        lua_State *L = luaL_newstate();
        luaL_openlibs(L);

        lua_call_function(L);

        lua_close(L);

        return 0;
}

Outputs …

Native to Lua

Build and run …

clang lua.c -I /usr/local/include -L /usr/local/lib -llua && ./a.out