I've been working on a short program that calculates the formula weight of a given molecular formula. Conceptually it is very easy, and I've done the same thing using Java and Python, but as practice I'm trying to use LiveCode to do the same thing. Input is a formula like: "C6H5Cl1". In the past I've parsed the input into linked lists, such as: (C,H,Cl) and (6,5,1). I then use the position in the linked lists to eventually calculate the formula weight after searching another set of lists with the periodic table in them.
What I have done so far works, and it is fast enough for my uses. What I am interested in knowing is if there is a more efficient way of doing the same thing, and if there are standard code writing protocols that I'm not observing that would make the code better. For example, I could use an array instead of two lists, but I don't know if speed or readability would improve.
Code: Select all
on mouseUp
put ("C","H","N","O","Cl","Br","S") into gElemDict --list of element symbols
put (12.01115,1.00794,14.0067,15.9994,35.453,79.904,32.064) into gNumDict --list of atomic weights of elements
put toUpper (text of fld "formula") into tMyVar --simplifies formatting
put "" into tElemList
put "" into tNumList
put "letter" into tCharType
repeat with i=1 to (the length of tMyVar)
put char 1 of tMyVar into tElem
delete char 1 of tMyVar
if matchText (tElem, "[A-Z]") is true then
if tCharType is "number" then put comma after tNumList
put tElem after tElemList
put "letter" into tCharType
else if isNumber (tElem) is true then
if tCharType is "letter" then put comma after tElemList
put "number" into tCharType
put tElem after tNumList
end if
end repeat
delete the last char of tElemList
repeat with i=1 to (number of items in tElemList)
get item i of tElemList
if (the length of it) = 2 then --element symbols can only be two letters, the second one is lower case by convention
put toLower (char 2 of it) into char 2 of item i of tElemList
end if
end repeat
put tElemList into fld "Field1"
put tNumList into fld "Field2"
put 0 into tTemp
repeat with i=1 to (number of items in tElemList)
put item i of tElemList into tElem
put item (itemOffset (tElem, gElemDict)) of gNumDict into tAtomicMass
put item i of tNumList into tNum
put (tNum * tAtomicMass) + tTemp into tTemp
end repeat
put tTemp into fld "Field3"
end mouseUp
Any comments? I made it work (mostly by trial and error), but would appreciate any feedback to help me program better.
Thanks,
--Doug