We will call our module MyDB. The module is part of the standard installation, so you don't have to create it with mShell→New Module:
![]() | ![]() | |
Instead, you can simply open
MyDb to look at the module code below:
|
/** A simple key-data database. */ use io, array, ui /** Load the database from a file. @param file the file to load the database from. @return the database. */ function load(file="table.dat") try f=io.open(file); table=io.readm(f); io.close(f); return table catch e by return [] end end |
|
/** Save the database to a file. @param table the database to save. @param file the file to save the database to. */ function save(table, file="table.dat") f=io.create(file); io.writem(f, table); io.close(f) end |
|
/** Present a user interface to edit a database. @param table the database to edit. */ function edit(table) while true do list=keys(table); array.sort(list); array.insert(list, 0, "<New>"); i=ui.list(list); if i=null then break end; i=i[0]; if i=0 then 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 k=list[i]; f=ui.form([k,"Text":table[k]+"\n"]); if f#null then table[k]=f["Text"] end end end end |
Remarks:
SmsService, which uses MyDB:
|
/** A configurable SMS service. */ use sms, mydb, ui const file="SmsService.dat"; db=mydb.load(file); ui.menu("Service",["Edit","Stop"]); do id=sms.receive(1000); if id#null then msg=sms.get(id); t=lower(trim(msg["text"])); if db[t]#null then print "Got",t,"from",msg["sender"]; sms.send(msg["sender"], db[t]); sms.delete(id) end end; cmd=ui.cmd(5000); if cmd="Edit" then mydb.edit(db); mydb.save(db, file) end until cmd="Stop" |
Remarks: