r/lua • • 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

20 comments sorted by

3

u/acw1668 5d ago edited 1d ago

Suggest to put similar code inside a function, for example:

function ask(prompt)
    print(prompt)
    return io.read()
end

nr1 = ask("What is your first number?")
op = ask("Operator (+,-,/,*)?")
nr2 = ask("What is your second number?")

Also you need to cater:

  • invalid number input
  • division by zero error

1

u/MundaneFoundation864 5d ago

Nice, I might use this for a future thing

2

u/SlaySike9944 5d ago

the trade off. is that you add function overhead. if you aim for micro optimization. you can't tell lua to inline the functions for you.

you have to get rid of the function etc in those cases.

when you have something like a png decoder written in pure lua is where the overhead matters.

writing your own C function and exposing it to lua would solve the speed problem. but not every lua environment is gonna let you do that.

3

u/Old_County5271 5d ago

If you're going to be worried about that, don't use lua and instead transpile to it that supports inline mode, no functions anywhere.

1

u/blobules 5d ago

This illustrates why function are so important. It us good to see that early when you learn to code.

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

1

u/MundaneFoundation864 5d ago

if i dont io.flush() the io.read() runs before the print

1

u/Old_County5271 5d ago

I've never needed to io.flush, what OS/lua are you using?

1

u/MundaneFoundation864 5d ago

Windows 11 home with whatever version the terminal command installed

1

u/Old_County5271 5d ago

Maybe you should setvflush"none" or whatever?

1

u/MundaneFoundation864 4d ago

the fuck is a setvflush

1

u/Old_County5271 4d ago edited 4d ago

Sorry, wrote the wrong thing and I'm fighting the GD Google keyboard which wants to write words instead of what I type. Anyway.

https://www.lua.org/manual/5.5/manual.html#pdf-file:setvbuf

It's io.flush but you set it for the file itself, you have three options, it's best to say the examples, in posix, print is a wrapper around io.stdout, so its doing io.stdout:write(args, currrent_os==windows and "\r\n" or "\n"), io.stdout is line buffered, io.stderr has no buffer, so it writes to the terminal immediately, no buffering happens, io.stdin is line buffered. I think you can set io.stdout:setvbuf"no" and it should immediately write to terminal without you flushing manually... I think. Windows is weird.

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!

3

u/SlaySike9944 5d ago

those libraries are written in C. lua is a dynamic GC interpreted language. using those C functions can in some cases be faster than writing it in lua.

that compromise doesn't exist when you write your code in c, c++, rust. but lua is simplicity first.

3

u/Old_County5271 5d ago

This is a terrible recommendation, I would agree if the library wasn't luasocket which is multiplatform and should be installed everywhere.

lfs, luasocket, lpeg, rex_lib are basic libraries which without them, pure lua is not worth using.

1

u/Bright-Historian-216 6d ago

to be fair, there is no "sleep" in base lua. as being more experienced, of course we know that the simplest solution is, for example, to just compare os.time in a loop, but this may not be necessarily obvious to an utter beginner.

3

u/Old_County5271 5d ago

That's not a solution, that is a hack.

1

u/c0gster 5d ago

Busy waiting is literally the worst way to wait in a program.

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

-- Recommended to use local variables 
local write = io.write
local nr1, nr2, op

-- Formatted this section for better readability 
write('What is your first number? ')
nr1 = io.read()

write('Operator? (+,-,/,*) ')
op = io.read()

write('What is your second number? ')
nr2 = io.read()

-- Removed the "socket" module here because it's not really necessary 
write('calculating...\n')

-- Hash tables are faster than a chain of if-else statements
local RESULTS = {['+'] = nr1 + nr2, ['-'] = nr1 - nr2, ['*'] = nr1 * nr2, ['/'] = nr1 / nr2}

if RESULTS[op] then
  print(RESULTS[op])
else 
  print('invalid operator')
end