Last active
December 30, 2015 17:39
-
-
Save griffgruff/7862364 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function split(str, delim, maxNb) | |
| -- Eliminate bad cases... | |
| if string.find(str, delim) == nil then | |
| return { str } | |
| end | |
| if maxNb == nil or maxNb < 1 then | |
| maxNb = 0 -- No limit | |
| end | |
| local result = {} | |
| local pat = "(.-)" .. delim .. "()" | |
| local nb = 0 | |
| local lastPos | |
| for part, pos in string.gfind(str, pat) do | |
| nb = nb + 1 | |
| result[nb] = part | |
| lastPos = pos | |
| if nb == maxNb then break end | |
| end | |
| -- Handle the last field | |
| if nb ~= maxNb then | |
| result[nb + 1] = string.sub(str, lastPos) | |
| end | |
| return result | |
| end | |
| StringCalculator = | |
| { | |
| defaultDelimiter = ",", | |
| delimiterPatternMatch = "//[^\n]" | |
| } | |
| function add(value) | |
| if value == "" then | |
| return 0 | |
| end | |
| delimiter = find_delimiter(value) | |
| value = remove_specified_delimiter_token(value) | |
| value = replace_delimiter_with_default(value, delimiter) | |
| result = split(value, ",") | |
| return Total_Numbers_In_Table(result) | |
| end | |
| function find_delimiter(value) | |
| delimiterToken = string.match(value,"//[^\n]") | |
| if (delimiterToken == nil) then | |
| return "," | |
| end | |
| value = string.gsub(value,"//","") | |
| delimiter = string.match(value,"[^\n]+") | |
| return delimiter | |
| end | |
| function remove_specified_delimiter_token (value, delimiter) | |
| delimiterToken = string.match(value,"//*.[^\n]") | |
| if (delimiterToken ~= nil) then | |
| value = string.gsub(value,delimiterToken .. "\n","") | |
| end | |
| return value | |
| end | |
| function replace_delimiter_with_default(value,delimiter) | |
| value = string.gsub(value, delimiter,"\,") | |
| return string.gsub(value,"\n",",") | |
| end | |
| function total_numbers_in_table(result) | |
| total = 0 | |
| for key,value in ipairs(result) do | |
| total = total + value -- negative numbers check | |
| end | |
| return total | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment