Is it possible to store an operator in an argument?

Hello. I’ve been working with some modulescripts as of late for ease of access, and I wanted to know if it was possible to store an operator in a function’s argument. For example, let’s say that I had:
local function mathFunction(value1, operator, value2)
Basically what this would do is that, when called, I’d do this:
mathFunction(1, +, 1)
However, I am unsure if this is possible. In my own attempts, I’d receive a syntax error. Is there any way to approach this>

I don’t see a problem with this?

I just answered my own question soon after. I’ll be closing this post now.

Operators are not expressions. So no. You could look into using loadstring, assuming this is a server script.

local function operation(lhs, operator, rhs)
    return loadstring("return " .. lhs .. operator .. rhs)()
end

Could you share your solution? The dev forum is a public resource, this could help future readers with the same issue

Oh. I’m using a if operator == “+” then it will do addition. Basically I’m just putting in the operator as a string.

that isn’t useable on local scripts
the solution using if statements is better

Yes, hence why I said “assuming this is a server script”.

I disagree – since Luau lacks switch statements, the closest and cleanest you can get is using a dictionary dispatch.

local operations = {
    ["+"] = function(lhs, rhs) return lhs + rhs end,
    ["-"] = function(lhs, rhs) return lhs - rhs end,
    -- etc
}

local function operation(lhs, operator, rhs)
    return operations[operator](lhs, rhs)
end
1 Like

I said if statements were better to use then loadstring

never did I ever say that there wasn’t something better then if statements

Could have been misinterpreted as it being objectively better, more so if you are talking with a user whose first language is not English.

But there could probably be an even better/smarter method than dictionary dispatches! These topics are always open to providing better methods
:slight_smile:

I agree, also do you know why loadstring can’t be used on local scripts?
I always wondered that but never looked it up

To make it harder for exploiters. Roblox removed the compiler from the client for the same reason, so the client is physically unable to compile code. But, as usual, exploiters got around it and implemented their custom loadstring

thank you for this
very helpful