\startluacode

do

    thirddata = thirddata or { }

    local molecule = { }
    
    function molecule.text(one)
        tex.sprint(string.format("%s",one))
    end

    function molecule.low(one,two)
        tex.sprint(string.format("%s\\low{%s}",one,two))
    end

    function molecule.high(one,two)
        tex.sprint(string.format("%s\\high{%s}",one,two))
    end

    function molecule.lowhigh(one,two,three)
        tex.sprint(string.format("%s\\lohi{%s}{%s}",one,two,three))
    end

    function molecule.highlow(one,two,three)
        tex.sprint(string.format("%s\\lohi{%s}{%s}",one,two,three))
    end

    local plus         = lpeg.P("+")
    local minus        = lpeg.P("-")
    local lowercase    = lpeg.R("az")
    local uppercase    = lpeg.R("AZ")
    local number       = lpeg.R("09")
    local subscript    = lpeg.P("_")
    local superscript  = lpeg.P("^")
    local leftbrace    = lpeg.P("{")
    local rightbrace   = lpeg.P("}")

    local single    = lowercase + number + plus + minus
    local multiple  = leftbrace * single^1 * rightbrace
    local content   = single + multiple 

    local text    = lpeg.C(uppercase^1)                                                                 / molecule.text
    local low     = lpeg.C(uppercase^1) * subscript   * lpeg.C(content)                                 / molecule.low
    local high    = lpeg.C(uppercase^1) * superscript * lpeg.C(content)                                 / molecule.high
    local lowhigh = lpeg.C(uppercase^1) * subscript   * lpeg.C(content) * superscript * lpeg.C(content) / molecule.lowhigh
    local highlow = lpeg.C(uppercase^1) * superscript * lpeg.C(content) * subscript   * lpeg.C(content) / molecule.highlow

    local parser = (lowhigh + highlow + low + high + text)^0

    function thirddata.molecule(string)
        parser:match(string)
    end

end

\stopluacode

\def\molecule#1{\ctxlua{thirddata.molecule("#1")}}

\starttext
\molecule{CO_2}
\molecule{H^+}
\molecule{H_2^+}
\molecule{C_nH_{2n+1}OH}
\stoptext
