How to use addOptionsMenuItem to put a multiple-choice option set in the System Menu

This is a simple one-off example. A more robust system could be created to generate multiple menu items, with the displayed option text and associated internal values all stored in tables! But FWIW I thought I'd just share this simple, minimal Lua example for addOptionsMenuItem, from retreiving the value that sets which option should be shown as selected, through to processing the user's choice.

Corrections/improvements/alternatives welcomed!

--First determine which option should already be selected when the menu opens ("storedValue" is assumed to be some variable--which need not be an integer--that exists in your game already):

local preSelectedMenuOption
if storedValue == 1 then --Whatever value was set previously by your game (maybe an initial default, maybe a prior hoice saved in playdate.datastore)
	preSelectedMenuOption = "option A"
elseif storedValue == 2 then
	preSelectedMenuOption = "option B"
else
	preSelectedMenuOption = "option C"
end

--Then create the menu item (its title will be forced to lowercase by the system, but capitalization of its options is in your control):

local sysMenu = playdate.getSystemMenu()
local menuItem, error = sysMenu:addOptionsMenuItem("title", {"option A", "option B", "option C"}, preSelectedMenuOption, function(value)
	setstoredValue(value)
end)

--This function runs when the system menu closes, if the user changed the option:

function setstoredValue(value)
	if value == "option A" then
		storedValue = 1
	elseif value == "option B" then
		storedValue = 2
	else
		storedValue = 3
	end
	
	--Take actions here to make use of the new "storedValue" (and save it to playdate.datastore for future sessions if desired)
end
3 Likes