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
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
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.
5 comments
It's wrong because the symbol is a string and therefore not by itself.
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.
Can you make me an example, i'm visual: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
I just dont know how to use loadstring loll