Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Can I custom a calcul with a string?

Hey guys, I've a good question for u today. I've been asking it for a while, how can I custom (+, -) in a calcul with a string? Little wrong example here.

local symbol = {[1] = '-', [2] = '+'}

print(1 symbol[1] 2) -- This is wrong

5 comments

0

It's wrong because the symbol is a string and therefore not by itself.

0

If you want to do a custom calculator, it's pretty easy. Have the input itself be a string, embed that string in a loadstring("return " .. number) embedded in an assert(), which will return a function that returns the evaluated expression. This function can be called and printed to have the expression calculated.

0

Can you make me an example, i'm visual:0

0

thats a pretty easy approach, although if you dislike using loadstring for any reason, you would have to use a more grueling method, making a A stack implemented infix notation expression parser 

0

I just dont know how to use loadstring loll

1 answer

✓ Accepted answer

Use a table of functions:

local ops = {
	["+"] = function(a, b) return a + b end,
	["-"] = function(a, b) return a - b end,
}
print(ops["+"](5, 3)) -- 8

This discussion is preserved as it was. New answers, comments, and votes are closed.