Making it a Function

We now have the bits and pieces together to create a function in m which edits any array of key-value pairs, for instance our db variable. We would like to have a function edit, which we can simply call, passing our database as a parameter:

edit(db)

And here is such a function:

function edit(table)
  while true do
    // display the list of keywords
    list=keys(table);
    array.sort(list);
    array.insert(list, 0, "<New>");
    i=ui.list(list);
    // if the user canceled, i is null
    if i=null then break end;
    i=i[0];
    if i=0 then // <New> was selected: add
      f=ui.form(["Key":"","Text":"\n"]);
      if f#null then
        k=f["Key"];
        if table[k]=null then table[k]=f["Text"]
        else ui.error(k + " already exists") end
      end
    else // an existing keyword was selected: edit
      k=list[i];
      f=ui.form([k,"Text":table[k]+"\n"]);
      if f#null then table[k]=f["Text"] end
    end
  end
end

So if we write

edit(db)

this means executing the function edit, passing our variable db to it. During the call, table=db, and all modifications to the elements of table are in fact modifications to the elements of db.

For an in-depth presentation of functions, refer to section * (Reference).


© 2004-2010 airbit AG, CH-8008 Zürich
Document AB-M-TUT-869