I'm trying to write something that takes input in the form of a function, such as "f(x) = 2*x 5", and have it be calculated as a normal equation.
What I currently have is:
print("give any function") --vague as placeholder
x=50
str=string.gsub(io.read(), "x", tostring(x))
print(str*1)
It works fine when you have the x variable in the input, replacing it with the previously set x variable as before. What happens is when you put something in such as "1 1", it doesn't accept it.
Is there a way to get input from something such as "1 1" to be calculable to 2, rather than just the string it is given as?
What I am essentially asking here: Any user input under the format "number operator number" only reads as a string, not a calculable equation. Any workaround?
CodePudding user response:
You can use some more detailed gsub and then load the function as lua code.
As the format of 1 1
is not really a "function" format we will need to add some extra handling for the case when the function is just an operation
function evaluateFunction(funcStr, x)
funcStr = "return " .. funcStr
funcStr, replaced = funcStr:gsub("f%(", "function(")
funcStr = funcStr:gsub("=", "return")
if replaced ~= 0 then
funcStr = funcStr .. " end"
end
print(funcStr)
local func = load(funcStr)()
if type(func) == "function" then
print(func(x))
else
print(func)
end
end
evaluateFunction("f(x) = 2*x 5", 50)
evaluateFunction("f() = 2*5")
evaluateFunction("1 1")
Output:
return function(x) return 2*x 5 end
105
return function() return 2*5 end
10
return 1 1
2