Lua Table Argument
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.
Create a Lua table, assign a value and pass it in as an argument …
#include <lua/lua.h>
#include <lua/lualib.h>
#include <lua/lauxlib.h>
void
lua_table_function(lua_State *L) {
const char * script_d = "function update(self)\n print(self.name)\n end";
luaL_dostring(L, script_d);
/* create table */
lua_getglobal(L, "update");
lua_createtable(L, 1, 0);
int table_index = lua_gettop(L);
lua_pushstring(L, "name");
lua_pushstring(L, "PlayerOne");
lua_settable(L, -3);
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_table_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