r/lua • u/MundaneFoundation864 • 6d ago
Project Made a calculator in lua (first serious project) what do you guys think?
print('What is your first number?')
io.flush()
nr1 = io.read()
print('Operator? (+,-,/,*)')
io.flush()
op = io.read()
print('What is your second number?')
io.flush()
nr2 = io.read()
print('calculating...')
require("socket").sleep(0.2)
if op == '+' then
print(nr1 + nr2)
elseif op == '-' then
print(nr1 - nr2)
elseif op == '*' then
print(nr1 * nr2)
elseif op == '/' then
print(nr1 / nr2)
else print('invalid operator')
end
26
Upvotes
3
u/acw1668 5d ago edited 1d ago
Suggest to put similar code inside a function, for example:
Also you need to cater:
2
u/Bright-Historian-216 6d ago
looks good! you most often don't need to io.flush() manually, but if it's the only way your code works, i guess you should keep it.
try these things next:
- make the program go to the beginning after the result
- use os.time and os.difftime to make your own sleep function; read about these in the lua reference manual
- a pretty difficult challenge for some time in the future: make a program that can calculate inputs like "(5+3)/2"; remember to account for zero division
5
u/Vazzeline 6d ago
Do not use exterrnal library if not necessary, try to solve the problem on Lua way. (socket). You should use number/string conversion functions to avoid input data errors. If possible then never divide any number by zero... If this is your first Lua program then you are on the right way. Happy coding!
1
u/Kwaleseaunche 5d ago
Well done.
1
u/Ipbunpak1 4d ago edited 4d ago
Very cool for a first project! I played around with your code a little bit on my own. EDIT: formatting and comments