Skip to content

MCM State Options

schlangster edited this page Mar 23, 2013 · 14 revisions

Introduction

State options have been added in MCM 2.0 to provide a better method of organizing the event handler code.

However, due to the fact that mod authors are already used to the classic API, or made huge menus that would take a long time to convert, state options will not replace the default API. But if you are interested in writing better code, or if you're facing scalability issues, consider using them.

The rest of this document assumes that you are already familiar with the basic MCM principles.

Motivation

As explained in the other guides, the original method of identifying single options is by option ID. A generic example:

int aOID
int bOID
...
int zOID

event OnPageReset(string page)
	aOID = AddToggleOption("A", true)
	bOID = AddToggleOption("B", true)
	...
	zOID = AddToggleOption("Z", true)
endEvent

event OnOptionSelect(int option)
	if (option == aOID)	; ... handle A
	elseIf (option == bOID)	; ... handle B
	...
	elseIf (option == zOID)	; ... handle Z
	endIf
endEvent

event OnOptionDefault(int option)
	if (option == aOID)	; ... handle A
	elseIf (option == bOID)	; ... handle B
	...
	elseIf (option == zOID)	; ... handle Z
	endIf
endEvent

event OnOptionHighlight(int option)
	if (option == aOID)	; ... handle A
	elseIf (option == bOID)	; ... handle B
	...
	elseIf (option == zOID)	; ... handle Z
	endIf
endEvent

The actual handler code is first grouped by event type, then a cascade of if statements selects it by option ID. While this clearly works, there are several issues with this approach:

  • The handlers responsible for a single option are spread across the whole script. As the number of options grows, this becomes increasingly difficult to manage. For example, if you want to change an option, you'll have to find and modify code at many separate locations.
  • You might also argue that as the number of option grows, it has to execute a lot of unnecessary checks, though performance is not the primary concern here.
  • Changes are rarely limited to a single location in the script, which makes it easier to introduce bugs and harder to find them later.

State options resolve these issues, because they allow to encapsulate the code responsible for an option in a single state:

event OnPageReset(string page)
	AddToggleOptionST("OPTION_A", "A", true)
	AddToggleOptionST("OPTION_B", "B", true)
	...
	AddToggleOptionST("OPTION_Z", "Z", true)
endEvent

state OPTION_A
	event OnSelectST()
	endEvent

	event OnDefaultST()
	endEvent

	event OnHighlightST()
	endEvent
endState

state OPTION_B
	event OnSelectST()
	endEvent

	event OnDefaultST()
	endEvent

	event OnHighlightST()
	endEvent
endState

...

state OPTION_Z
	event OnSelectST()
	endEvent

	event OnDefaultST()
	endEvent

	event OnHighlightST()
	endEvent
endState
Clone this wiki locally