Websites Navigation: Airbit | Shop | m-shell.net
Languages: EN | DE

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

  • A function is defined by the keyword function, followed by its name, and the argument list in parentheses (). Here, there is a single argument, table, which is the array we want to edit (if there are multiple arguments, separate them by commas).
  • The following code up to the corresponding end is the body of the function, which will be executed each time it is called.
  • All variables inside the function, including the arguments, are local to the function; they are not the same variables as those outside the function. For instance, the statement

    list=keys(table)

    only modifies the variable list in the function, not any other variable with this name used outside the function or in another function.

  • The whole editing process is put into a loop, which is repeated until the user cancels the list dialog. If this happens, i=null, and the break statement is executed, leaving the loop and eventually returning from the function.
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-2011 airbit AG, CH-8008 Zürich
Document AB-M-TUT-887
mShell Home  > Documentation  > Manuals