Skip to content

Instantly share code, notes, and snippets.

@hoelzro
Created December 6, 2011 19:44
Embed
What would you like to do?
#include <lua.h>
#include <lauxlib.h>
#include <stdio.h>
static int greeting_key = LUA_NOREF;
static int mymodule_greet(lua_State *L)
{
const char *greeting;
if(greeting_key == LUA_NOREF) {
greeting = "Hello!";
} else {
lua_rawgeti(L, LUA_REGISTRYINDEX, greeting_key);
greeting = lua_tostring(L, -1);
lua_pop(L, -1);
}
printf("%s\n", greeting);
return 0;
}
static int mymodule_configure(lua_State *L)
{
lua_pushvalue(L, 2);
greeting_key = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pushvalue(L, 1);
return 1;
}
int luaopen_mymodule(lua_State *L)
{
lua_newtable(L);
lua_pushcfunction(L, mymodule_greet);
lua_setfield(L, -2, "greet");
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setmetatable(L, -3);
lua_pushcfunction(L, mymodule_configure);
lua_setfield(L, -2, "__call");
lua_pop(L, 1);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment