Pastey NEWT :: selecting an item from a listbox - Using pointer

include ../newt.e
include std/machine.e 
procedure main() 
 
-- create a simple list of things 
sequence fruits = { "Apples", "Bananas", "Oranges" } 
 
    newtComponent form, 
        listbox, 
        buttonSubmit 
 
    newt:Init() 
    newt:Cls() 
 
    newt:CenteredWindow( 64, 24, "*Select Item" ) 
 
 -- create a new list box 
    listbox = newt:Listbox( 2, 2, 5, NULL ) 
--  listbox = newt:Listbox( 2, 2, 5, NEWT_FLAG_RETURNEXIT ) 
--  listbox = newt:Listbox( 18, 3, 10, NEWT_FLAG_SCROLL ) 
--  listbox = newt:Listbox( 18, 3, 10, NEWT_FLAG_SCROLL ) 
--  newt:ListboxAppendEntry(listbox, "", 0) 
--  newt:ListboxAppendEntries(listbox, fruits, 0) 
 
  -- loop through the items 
  for index = 1 to length( fruits ) do 
 
            -- allocate some memory 
           atom ptr = allocate( 4 ) -- 1 = automatically free 
 
            -- store the index of this item 
            poke4( ptr, index ) 
 
            --  add the item to the list box 
     newt:ListboxAppendEntry( listbox, fruits[index], ptr ) 
  end for 
 
    buttonSubmit = newt:Button( 22, 20, "Submit" ) 
 
    form = newt:Form( NULL, NULL, 0 ) 
    newt:FormAddComponents( form, { 
        listbox, 
        buttonSubmit 
        }) 
 
    --// run the form here //-- 
    newt:FormRun(form) 
 
    -- get the selected "item" (our pointer above) 
    atom ptr = newt:ListboxGetCurrent( listbox ) 
 
    -- fetch the index from the pointer 
    integer index = peek4s( ptr ) 
 
    free(ptr) 
 
    newt:FormDestroy(form) 
    newt:Finished() 
    printf( 1, "you selected: %s\n", {fruits[index]} ) 
end procedure 
main()

1. Comment by gbonvehi May 09, 2013

Just for the records, this has a memory leak since It does not deallocate all items memory but just the selected one.