Accessing a read only metatable in c
===

I'm fairly new to Lua and still slightly struggling understanding the stack in Lua.

At the moment I'm trying to create a function in C++ that will add a Lua user function to an event manager.

I have added enumerations to Lua for my events using http://tdistler.com/2010/09/13/c-enums-in-lua this example. I have a function called AddEvent which is registered in Lua and takes 2 parameters a Event enumeration and a Lua function.

The implementation is as followed:


    int AddEvent(lua_State* LS)
    {
    	if (CheckFuncArg(LS, "AddEvent", 2))
    	{
    		if (lua_isEnumType(LS, "Events", -2))
    		{
    			//create a new event
    			EventList* newEvent = new EventList;
    			
    			//set the event ID that will be triggered when the event is active
    			newEvent->EventID = (Events)lua_toenum(LS, -2);
    			//create a new table for the registry index
    			lua_newtable(LS);
    			newEvent->Lua_Ref = luaL_ref(LS, LUA_REGISTRYINDEX);
    			printf("Lua Ref = %d\n", newEvent->Lua_Ref);
    			m_Events.push_back(newEvent);
    
    		}
    		else
    		{
    			printf("Error Invalid Enum Table\n");
    			return 0;
    		}
    		
    	}
    	return 1;
    }

The Functions lua_isEnumType and lua_toenum are defined as followed:

    bool lua_isEnumType(lua_State* LS, const char* tableName, int index)
    {
    	stackdump_g(LS);
    	lua_pushstring(LS, "type");
    	stackdump_g(LS);
    	lua_gettable(LS, index-1);
    	if(!lua_isnil(LS, -1))
    	{
    		const char* type = lua_tostring(LS, -1);
    		stackdump_g(LS);
    		if (strcmp(type, tableName) == 0)
    		{
    			lua_pop(LS, 1);
    			return true;
    		}
    	}
    	lua_pop(LS, 1);
    	return false;
    }

    int lua_toenum(lua_State* LS, int index)
    {
    	lua_pushstring(LS, "value");
    	lua_gettable(LS, index-1);
    	return luaL_checkint(LS, -1);
    }
then when the event is trigger it will call the RunEvent function that will call the function

    bool RunEvent(lua_State* LS, int ID)
    {
    	lua_rawgeti(LS,LUA_REGISTRYINDEX,m_Events[ID]->Lua_Ref);
    	if (lua_pcall(LS, 0, 0, 0) != 0)
    	{
    		printf("Error %s\n", lua_tostring(LS, -1));
    	}
    	return true;
    }

I think I need to go through the Lua book a few more times to work it out i'm still a little confused as to how the stack fully works.

