Phil CK

Lua Table Instance Call

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.

Create a function inside a table, alter the table, and pass it to the function.

#include <lua/lua.h>
#include <lua/lualib.h>
#include <lua/lauxlib.h>

lua_table_instance_functions(lua_State *L) {
        const char * script_e = "player = {name = \"foo\"}\nfunction player.update(self)\n print(\n end";
        luaL_dostring(L, script_e);

        /* alter table */
        lua_getglobal(L, "player");
        lua_pushstring(L, "name");
        lua_pushstring(L, "PlayerOne");
        lua_settable(L, -3);

        /* function call */
        lua_getglobal(L, "player");
        int index = lua_gettop(L);
        lua_getfield(L,index, "update");
        lua_getglobal(L, "player");

        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));

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



        return 0;

Outputs …

Lua to Native

Build and run …

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