Skip to content

Instantly share code, notes, and snippets.

@ghiculescu
Last active March 18, 2016 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghiculescu/b5dac57df1e7301002c9 to your computer and use it in GitHub Desktop.
Save ghiculescu/b5dac57df1e7301002c9 to your computer and use it in GitHub Desktop.
Calculator = {}
function Calculator:new (o, input) -- the "account" example at http://www.lua.org/cgi-bin/demo made me think that you could just make classes, didn't realise the importance of all this boilerplate
o = o or {name=name}
setmetatable(o, self)
self.__index = self
self.input = input
self.calculation = "(%d+) ?([+-/*]) ?(%d+)" -- not sure if i'm a fan of lua not supporting all regex features - http://lua-users.org/wiki/PatternsTutorial - but i suspect the benefits will be obvious after more digging
return o
end
function Calculator:result () -- forgot the brakcets here - debugging that was confusing
local first_num, method, last_num = string.match(self.input, self.calculation) -- was pleased to see you could do this
if method == "+" then -- seems dumb that "then" is required
return first_num + last_num
elseif method == "-" then
return first_num - last_num
elseif method == "*" then
return first_num * last_num
elseif method == "/" then
return first_num / last_num
end
end
print(Calculator:new(nil, "1 + 1"):result()) -- 2 <-- i'm spoiled by ruby. forgot the method call braces() for ages.
print(Calculator:new(nil, "22 + 14"):result()) -- 36
print(Calculator:new(nil, "22 - 14"):result()) -- 8
print(Calculator:new(nil, "10 / 5"):result()) -- 2
print(Calculator:new(nil, "10 * 5"):result()) -- 500
print(Calculator:new(nil, "10 / 9"):result()) -- 1.1111111111111 <-- cool, didn't expect it to do floats automatically. it also parsed the string correctly.
@daveallie
Copy link

Where's the support for multiple operators and order of operations?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment