# Calculator with just one textbox

Hello everyone,

So recently, I’m working on a calculator for my upcoming game. And I want to make it as advanced as possible. So, I thought of the idea of making it calculating two numbers with a valid operator in just one textbox

Here’s a concept:

The problem is, how can I do that? The idea is simple, check how many numbers are in the textbox eg: 23 65 (two numbers), 45 87 102 (three numbers), and with the help of `string.find()` we can find the operator to calculate the result of two numbers together with it. And also there shouldn’t be three numbers separated in one textbox.

Any help is appreciated! Thanks

string.split(textbox.Text, " ") would give you a table containing every argument

If you had 5 * 9 it would be {5, “*”, 9}

1 Like

You’d have to write a full lexer, parser, and interpreter for this kind of thing. There’s plenty of tutorials online.

2 Likes

If you’re ok with using loadstrings, I have an entire guide on parsing math expressions:

The key points are:

1. Interpret it as a Lua expression
`2*x^2` becomes `function() return 2*x^2 end` where `x` is a predefined value supplied by an iterator or something
2. Supply it with the math library and use them as globals within the function
you would use `getfenv()` or `setfenv()` for this
3. Sanity check
You really want to make sure people don’t do anything bad with loadstrings so you will need a lot of safety checks, such as wiping out the entire default environment and blacklisting Lua keywords to prevent the execution of lambda functions
2 Likes

If the loadstring is being used only on the client, there’s no extra security risk, unless the user can use the calculator textbox as an executor.

1 Like

Last time I checked `loadstring` can only be run on the server. Doing it on the client would require a custom Lua sandbox module which is still feasible.

1 Like

Thank you all! I will try every single solution of yours!