#include "EABaseTypesLua/stackcheck.h"
#include "EAAssert/eaassert.h"

#include "lua.h"
#include "lauxlib.h"

namespace EA
{
	namespace Lua
	{
		StackCheck::StackCheck(lua_State* L, int exitStackDelta /*= 0*/)
			: mL(L)
			, mEntryStackCount(0)
			, mExitStackDelta(exitStackDelta)
		{
			mEntryStackCount = lua_gettop(mL);
		}
		
		StackCheck::~StackCheck()
		{
			CheckStack();
			mL = NULL;
		}
		
		void StackCheck::SetExitStackDelta(int exitStackDelta)
		{
			mExitStackDelta = exitStackDelta;
		}

		bool StackCheck::CheckStack()
		{
			bool result = true;
			int curStackCount = lua_gettop(mL);
			if(curStackCount - mEntryStackCount != mExitStackDelta)
			{
				EA_FAIL_FORMATTED(("Lua Stack Verification failure, entry stack count = %d, expected exit delta = %d, actual exit delta = %d", mEntryStackCount, mExitStackDelta, curStackCount - mEntryStackCount));
				result = false;
			}
			return result;
		}
	}
}
