Search code examples
luachemistry

Molecular weight calculator in Lua


As my first real program in Lua, I'd like to create a molecular weight calculator (similar to the one here: http://www.lenntech.com/calculators/molecular/molecular-weight-calculator.htm )

I'd like some help with the first step of this program. My first step should be take the users input as a string, and than to split the string. I am looking at http://lua-users.org/wiki/StringLibraryTutorial and trying to figure out how to do this. When the user input is CH4 the program should split this string into C, and H4. Here is my code:

H   = 1.008
C   = 12.011
N   = 14.007
O   = 15.999

io.write("Enter molecular formula")
input = io.read()

result = 
print("the molecular weigth is" .. result)

Can someone show me how I can accept the user input as a string and how to split that string?

Edit: as requested, I have been more specific in my exact question


Solution

  • Here's a possible way that you can start with:

    1. Get the input string from standard input:

      input = io.read()
      
    2. Convert the string like Cr(NO2)2 to a string Cr+(N+O*2)*2. The nature of chemical element names is that it all begins with a uppercase letter, and followed by zero or more lowercase letters, so the rule could be: whenever a uppercase letter or a "(" is encountered (except when it's the first or preceded by a "(" ), insert a "+" before it, whenever a number is encountered, insert a "*" before it.

    3. Calculate the result from the string Cr+(NO*2)*2, that's the beauty of Lua, it's a legal Lua expression, so just load the string and get the result:

      str = "Cr+(N+O*2)*2"
      func = assert(load("result = " .. str))
      func()
      
      print("the molecular weigth is" .. result)
      

    In Lua 5.1, use loadstring() in the place of load().