#include #define LUA2C "Lua2C" typedef struct { int fastCnt; int slowCnt; } Lua2C; static int Lua2C_fast(lua_State *L) { Lua2C* l2c = (Lua2C*)luaL_checkudata(L,1,LUA2C); l2c->fastCnt++; lua_pushinteger(L, l2c->fastCnt); lua_pushinteger(L, l2c->slowCnt); return 2; } static int Lua2C_slow(lua_State *L) { Lua2C* l2c = (Lua2C*)luaL_checkudata(L,1,LUA2C); ThreadMutex* m = balua_getmutex(L); balua_releasemutex(m); Thread_sleep(5000); /* 5 secs */ balua_setmutex(m); l2c->slowCnt++; lua_pushinteger(L, l2c->slowCnt); lua_pushinteger(L, l2c->fastCnt); return 2; } /* Garbage Collect callback */ static int Lua2C_gc(lua_State *L) { Lua2C* l2c = (Lua2C*)luaL_checkudata(L,1,LUA2C); /* Destructor code here */ return 0; } static int Lua2C_open(lua_State *L) { Lua2C* l2c = (Lua2C*)lua_newuserdata(L, sizeof(Lua2C)); l2c->slowCnt = 0; l2c->fastCnt = 0; /* Get metatable for Lua2C */ if(luaL_newmetatable(L, LUA2C)) { /* Failed getting meta i.e. first time this func is called. */ static const luaL_Reg Lua2CLib[] = { {"fast", Lua2C_fast}, {"slow", Lua2C_slow}, {"__gc", Lua2C_gc}, {NULL, NULL} }; /* Create metatable */ lua_pushvalue(L, -1); /* Push table (t) created by luaL_newmetatable */ lua_setfield(L, -2, "__index"); /* t.__index == t */ /* Set t.fast=Lua2C_fast, t.slow=Lua2C_slow, and t.__gc=Lua2C_gc */ luaL_setfuncs(L, Lua2CLib,0); } lua_setmetatable(L, -2); /* Set meta for Lua2C userdata */ return 1; /* Lua2C userdata */ } /* End */ static int installLua2C(lua_State *L) { static const luaL_Reg mdfTable[] = { {"open", Lua2C_open}, {NULL, NULL} }; luaL_newlib(L, mdfTable); return 1; } /* End */ int luaopen_Lua2C(lua_State* L) { luaL_requiref(L, "Lua2C", installLua2C, TRUE); return 1; }