Skip to content

Instantly share code, notes, and snippets.

@echiesse
Created March 15, 2019 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save echiesse/adbd7cfbd2847f34cd2504ca5295830b to your computer and use it in GitHub Desktop.
Save echiesse/adbd7cfbd2847f34cd2504ca5295830b to your computer and use it in GitHub Desktop.
Setting a metatable inside a table from C API
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<lua.h>
#include<lualib.h>
#include<lauxlib.h>
int main()
{
char *scriptName = "script.lua";
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_newtable(L); // table
lua_newtable(L); // table | subtable
lua_setfield(L, -2, "subtable"); // table
lua_getfield(L, -1, "subtable"); // table | subtable
lua_getfield(L, -2, "subtable"); // table | subtable | subtable
lua_setfield(L, -2, "__index"); // table | subtable
lua_setmetatable(L, -2); // table
lua_setglobal(L, "A");
luaL_loadfile(L, scriptName); // scriptFunction
lua_call(L, 0, LUA_MULTRET, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment