Phil CK

Lua Table Edit

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.

Edit a table …

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

lua_table(lua_State *L) {
        const char * script = "table_one = { name = \"Unknown\", score = 123} \n function tab_print(tab)\n for k,v in pairs(tab) do print(k,v) end\n end";
        luaL_dostring(L, script);

        /* update table */
        lua_getglobal(L, "table_one");
        int index = lua_gettop(L);

        lua_pushstring(L, "name");
        lua_pushstring(L, "PlayerOne");
        lua_settable(L, index);

        /* call function */
        lua_getglobal(L, "tab_print");
        lua_getglobal(L, "table_one");

        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 …

name    PlayerOne
score   123

Build and run …

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