Search code examples
luaiup

How to display a progress Bar using Lua and IUP


I have built a long running script to which I have added a progress bar with the following code:

function StartProgressBar()
   gaugeProgress = iup.gaugeProgress{}
   gaugeProgress.show_text = "YES"
   gaugeProgress.expand = "HORIZONTAL"
   dlgProgress = iup.dialog{gaugeProgress; title = "Note Replacement in Progress"}
   dlgProgress.size = "QUARTERxEIGHTH"
   dlgProgress.menubox = "NO"  --  Remove Windows close button and menu.
   dlgProgress:showxy(iup.CENTER, iup.CENTER)  --  Put up Progress Display 
   return dlgProgress
end

This is called before the loop and the progress bar updated during the loop (I am not calling MainLoop). At the end of the process I call dlgProgress.destroy to clear it.

As long as I don't take focus from the progress bar it works fine, but if focus is lost the program crashes, so I am sure I am doing this the wrong way. Can any one tell me the correct way. A detailed google did not find me any examples for iup, lua progress bars.

Thank you in advance.


Solution

  • Here is a working sample.

    require "iuplua"
    
    local cancelflag
    local gaugeProgress
    
    local function StartProgressBar()
        cancelbutton = iup.button {
            title = "Cancel",
            action=function()
                cancelflag = true
                return iup.CLOSE
            end
        }
        gaugeProgress = iup.progressbar{ expand="HORIZONTAL" }
        dlgProgress = iup.dialog{
            title = "Note Replacement in Progress",
            dialogframe = "YES", border = "YES",
            iup.vbox {
                gaugeProgress,
                cancelbutton,
        }
        }
        dlgProgress.size = "QUARTERxEIGHTH"
        dlgProgress.menubox = "NO"  --  Remove Windows close button and menu.
        dlgProgress.close_cb = cancelbutton.action
        dlgProgress:showxy(iup.CENTER, iup.CENTER)  --  Put up Progress Display
        return dlgProgress
    end
    
    
    dlg = StartProgressBar()
    gaugeProgress.value = 0.0
    
    for i=0,10000 do
        -- take one step in a long calculation
        -- update progress in some meaningful way
        gaugeProgress.value = i / 10000
        -- allow the dialog to process any messages
        iup.LoopStep()
        -- notice the user wanting to cancel and do something meaningful
        if cancelflag then break end
    end
    
    -- distinguish canceled from finished by inspecting the flag
    print("cancled:",cancelflag)
    

    I've used IUP 3.0, and its standard Lua binding here. The gauge control is named iup.progressbar in IUP 3.0, and was named iup.gauge in earlier versions. In earlier versions it may have been in the extended controls library as well.

    I've tested this on Windows. One assumes it has similar behavior on other platforms, but your mileage may vary.