#define cb_c
#define LUA_LIB


extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include <stdlib.h>
#include <string.h>
#include <stdio.h>


static lua_State	*gpLuaState = 0;		// Used by callback function to send status to the script.
static int cbNewData( lua_State * );
void fnCallback( int, int, int  );


static int cbNewData( lua_State *L )
{
	int a, b, c;

	a = luaL_checkint( L, 1 );
	b = luaL_checkint( L, 2 );
	c = luaL_checkint( L, 3 );

	fnCallback( a, b, c );

	return 0;
}



void  fnCallback( int nEvent, int nParam1, int nParam2 )
{
	int stat;

	if (gpLuaState != 0)
	{
		lua_getglobal( gpLuaState, "cbCallback" );
		lua_pushinteger( gpLuaState, nEvent );
		lua_pushinteger( gpLuaState, nParam1 );
		lua_pushinteger( gpLuaState, nParam2 );

		// do the call ( 3 arguments, no return, no error function )
		if (stat = lua_pcall( gpLuaState, 3, 0, 0 ) != 0 )
		{
			printf("eipCallback failed, code %d - %s", stat, lua_tostring(gpLuaState, -1));
			lua_pop(gpLuaState, 1);
		}
	}
	else
	{
		printf("gpLuaState was not initialized");
	}
}


static const luaL_Reg cblib[] = {
  {"write", cbNewData},
  {NULL, NULL}
};


LUALIB_API int luaopen_cb (lua_State *L) {
  gpLuaState = L;
  /* open library */
  luaL_register(L, "cb", cblib);
  return 1;
}
