dm-script

How can I safely check if a submenu exists in GMS UI using DM script?


I'm working with the GMS UI and have a menu structure where a main menu may or may not have a specific submenu. My goal is to check for the existence of a submenu without triggering an error if it doesn't exist.

My current approach is:

Object MB = GetMenuBar()
Object Menu = MB.FindMenuItemByName("Menu")
Object SubMenu = Menu.FindMenuItemByName("SubMenu")
Result(SubMenu.GetName())

The issue is that if the submenu doesn't exist, the call to Menu.FindMenuItemByName("SubMenu") results in an error, even when I try to wrap the code in a try-catch block.

Questions:

  1. Is there a built-in or recommended method in DM script to verify the existence of a submenu before accessing its properties?
  2. How can I modify my script to safely check for the submenu's existence and handle cases where it isn't present, without causing an error?

Any insights, workarounds, or example code would be greatly appreciated. Thank you!


Solution

  • Generally, when using functions/methods (such as FindMenuItemByName) that return references to objects, it is a good idea to use the method ScriptObjectIsValid to test whether the returned object is valid and to branch one's code accordingly. So in your example, you would probably want to do something like the following:

    Object MB = GetMenuBar()
    Object Menu = MB.FindMenuItemByName("Menu")
    if (Menu.ScriptObjectIsValid())
    {
        Object SubMenu = Menu.FindMenuItemByName("SubMenu")
        if (SubMenu.ScriptObjectIsValid())
            Result(SubMenu.GetName() + "\n")
        else
            Result("No sub-menu\n")
    }
    

    One can also do this via try-catch, but it's not particularly clearer (or cleaner), as follows:

    Object MB = GetMenuBar()
    Object Menu = MB.FindMenuItemByName("Menu")
    if (Menu.ScriptObjectIsValid())
    {
        try
        {
            Object SubMenu = Menu.FindMenuItemByName("SubMenu")
            Result(SubMenu.GetName() + "\n")
        }
        catch
        {
            Result("No sub-menu\n")
            break
        }
    }