You need to differ between guildIndex and guildID.
guildIndex is what you get when you use GetNumGuilds() and it will always be 1 to number of guilds, guildID is an arbitrary number and cannot be known before using GetGuildId(guildIndex). Don't assume that guildID is in the range 1-5 or even in the "correct" order. guildIndex will always reflect the order you joined the guilds in, but the index might change if you leave a guild. If you want to save something for a guild, it's safest to use the guild name, as this will never change.
If you use the guild joined and left events
Code:
EVENT_GUILD_SELF_JOINED_GUILD (integer eventCode, integer guildId, string guildName)
EVENT_GUILD_SELF_LEFT_GUILD (integer eventCode, integer guildId, string guildName)
there is also another catch: The guildId is not the local guildId, but for some reason the server-wide id of the guild. So for example when you create a new guild, you get the number of guilds that have been created so far on that server, as it seems to be a simple incremental id.
In order to get the local id you need to use this code inside the eventhandler:
Lua Code:
local guildId = GetGuildId(GetNumGuilds())
edit: For iterating over all your guilds, use this code:
Lua Code:
for guildIndex = 1, GetNumGuilds() do
local guildId = GetGuildId(guildIndex)
-- do something
end