luaiup

Populating an iup list from a lua table


I'm building up a set of IUP dialog 'helper' functions -- boilerplate that I can include in my Lua code to quickly implement frequently used interface functionality in a consistent manner.

I have a function to make a "standard" iup list with a callback:

function MakeList(funcSelect)
    return iup.list{
        valuechanged_cb = function(self)
            funcSelect()
        end,
        sort = "YES", dropdown = "YES", editbox = "NO",
        expand = "YES", visibleitems = "5"}
end

but I now want to enhance it to optionally populate it with a list of static values, so that I can call for example mylist = MakeList(myFunction, {"X", "B", "Q"}) where the function spec is function MakeList(funcSelect, tblVals) and return the list populated if the table of values is given as (the equivalent) of

iup.list{"X", "B", "Q";
        valuechanged_cb = function(self)
            funcSelect()
        end,
        sort = "YES", dropdown = "YES", editbox = "NO",
        expand = "YES", visibleitems = "5"}

but (eventually) not populated if the table of values is not specified or empty -- that's stage 2 of the problem.

The list will be populated before the mapping; I know how to do it after mapping using myList.APPENDITEM but for static lists that shouldn't be necessary (should it?)

I've tried

function MakeStaticList(funcSelect, tblVals)
    return iup.list{table.unpack(tblVals);
        valuechanged_cb = function(self)
            funcSelect()
        end,
        sort = "YES", dropdown = "YES", 
        editbox = "NO", expand = "YES", visibleitems = "5"}
end

but that trips over this behaviour: Lua unpack() messing arguments so only the first item in the table is added to the list.

I've also tried

function MakeStaticList(funcSelect, tblVals)
    l = iup.list{valuechanged_cb = function(self)
            funcSelect()
        end,
        sort = "YES", dropdown = "YES", editbox = "NO", expand = "YES", visibleitems = "5"}
      for i, v in ipairs(tblVals) do
            l[tostring(i)]=v
      end
    return l
end

and that works, but is there a neater way of doing it?

I want to crack the populating problem first and then move on to the optionality of the table of values after that.

Environment is Lua 5.1 with the compat-5.3 module.


Solution

  • IN case it helps anyone, what I finally did was (catering for indexed and non-indexed lists):

        local function PopulateList(l, tblVals)
            local is_indexed = (rawget( tblVals, 1 ) ~= nil)
            if not is_indexed then
                local i=1
                for k, _ in pairs(tblVals) do
                    l[tostring(i)]=k
                    i=i+1
                end
            else
                for i, v in ipairs(tblVals) do
                    l[tostring(i)]=v
                end 
            end
        end