#include "windows.h" extern "C" { #include "math.h" #include "string.h" #include "stdio.h" #include "stdlib.h" #include "lua/lua.h" #include "lua/lauxlib.h" #include "lua/lualib.h" } template class CStack { public: static enum {CStack_StackEmpty, CStack_BadMemory}; unsigned int slots() { return StackSize; } unsigned int size() { return StackIter; } bool empty() { return StackIter == 0; } T pop() { if(StackIter == 0) throw (int)CStack_StackEmpty; return _Stack[--StackIter]; } void push(T j) { if(StackSize >= StackIter && _Stack != 0) { T* _newstack = (T*)malloc(sizeof(T) * (StackSize + 1)); if(_newstack == NULL) { free(_newstack); this->~CStack(); throw (int)CStack_BadMemory; } for(int i=0;i~CStack(); throw (int)CStack_BadMemory; } } _Stack[StackSize++] = j; StackIter = StackSize; } void clear() { StackIter = 0; } CStack() { StackIter = StackSize = 0; _Stack = NULL; } ~CStack() { free(_Stack); StackIter = StackSize = 0; } private: unsigned int StackSize, StackIter; T* _Stack; }; CStack *LuaStack = NULL; extern "C" { int __declspec(dllexport) luaopen_stack (lua_State *L); } static int luaStack_Create(lua_State *Lua) { if(LuaStack != NULL) { luaL_error(Lua, "Stack already created!"); return 0; } LuaStack = new CStack(); return 0; } static int luaStack_Close(lua_State *Lua) { if(LuaStack == NULL) { luaL_error(Lua, "Stack is not created!"); return 0; } delete LuaStack; LuaStack = NULL; return 0; } static int luaStack_Push(lua_State *Lua) { if(LuaStack == NULL) { luaL_error(Lua, "Stack is not created!"); return 0; } LuaStack->push(lua_tonumber(Lua, 1)); return 0; } static int luaStack_Pop(lua_State *Lua) { if(LuaStack == NULL) { luaL_error(Lua, "Stack is not created!"); return 0; } try { lua_pushnumber(Lua, LuaStack->pop()); } catch (int e) { switch(e) { case static_cast(CStack::CStack_StackEmpty): lua_pushstring(Lua, "Stack is empty!"); break; } } return 1; } static int luaStack_Clear(lua_State *Lua) { if(LuaStack == NULL) { luaL_error(Lua, "Stack is not created!"); return 0; } LuaStack->clear(); return 0; } static int luaStack_Size(lua_State *Lua) { if(LuaStack == NULL) { luaL_error(Lua, "Stack is not created!"); return 0; } lua_pushnumber(Lua, LuaStack->size()); return 1; } static int luaStack_Empty(lua_State *Lua) { if(LuaStack == NULL) { luaL_error(Lua, "Stack is not created!"); return 0; } lua_pushboolean(Lua, LuaStack->empty()); return 1; } static int luaStack_Length(lua_State *Lua) { if(LuaStack == NULL) { luaL_error(Lua, "Stack is not created!"); return 0; } lua_pushnumber(Lua, LuaStack->slots()); return 1; } int __declspec(dllexport) luaopen_stack (lua_State *L) { printf("Stack loaded!\n"); struct luaL_reg driver[] = { {"push", luaStack_Push}, {"pop", luaStack_Pop}, {"clear", luaStack_Clear}, {"size", luaStack_Size}, {"empty", luaStack_Empty}, {"create", luaStack_Create}, {"close", luaStack_Close}, {"length", luaStack_Length}, {NULL, NULL} }; luaL_openlib (L, "stack", driver, 0); return 1; };