Search code examples
dm-script

How to know whether GMS UI has a sub-menu


In GMS UI, I have a menu, which has a sub menu. I'd like to confirm whether the sub menu exists in dm-script.

If the sub menu exists, I can use the code below to get the name. But if the sub menus doesn't exist, it will give error. At first, I try to use try-catch structure to avoid the error and make the code work. But it seems still give the error.

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

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
        }
    }