luaiup

Iup Lua callback -- what am I doing wrong?


I'm using Lua 5.1 with IUP 3.5, and trying to use a list callback to populate an Address list depending on the Place selected. (The list is an editbox, so I will need to handle that in due course, but let us deal with the basics first). I've clearly got a fundamental misunderstanding of how to do this.

The code:

function MakeAnIupBox
    --make some more elements here
    listPlace = iup.list{}
    listPlace.sort = "YES"
    listPlace.dropdown = "YES" 
    --populate the list here
    --now handle callbacks
    listPlace.action = function(self) PlaceAction(text, item,  state) end
end

function PlaceAction(text, item, state)
    listAddress.REMOVEITEM = "ALL"
    if state == 1 then -- a place has been selected
    --code here to populate the Addresses list
    end
end

The iup documentation describes the action callback for a list as

ih:action(text: string, item, state: number) -> (ret: number) [in Lua]

However, when I run this code I get:

I've also tried coding the callback as

function MakeAnIupBox
    --make some more elements here
    listPlace = iup.list{}
    listPlace.sort = "YES"
    listPlace.dropdown = "YES" 
    --populate the list here
end
function listPlace:action (text, item, state)
    listAddress.REMOVEITEM = "ALL"
    if state == 1 then -- a place has been selected
        --code here to populate the Addresses list
    end
end 

but that fails to run: the error is attempt to index global 'listPlace' (a nil value)

I'd prefer not to embed the callback in "MakeAnIupBox" because I'm hoping to make it (and the other associated callbacks) a resuable component in several Lua programmes that all process similar datasets but from different UIs.


Solution

  • Building on the suggestion of Antonio Scuri which was not totally explicit, I have worked out that the code needs to read:

    function MakeAnIupBox
        --make some more elements here
        listPlace = iup.list{}
        listPlace.sort = "YES"
        listPlace.dropdown = "YES" 
        --populate the list here
        --now handle callbacks
        listPlace.action = function(self, text, item, state) PlaceAction(listPlace, text, item,  state) end
    end
    
    function PlaceAction(ih, text, item, state)
        listAddress.REMOVEITEM = "ALL"
        if state == 1 then -- a place has been selected
        --code here to populate the Addresses list
        end
    end