How add code to an function code based on input? (automatically)

Hello everyone!

I have no clue how I can automatically add code to an function automatically based on the input.

If the input for example is + is used for calculations with numbers, for example 1+1 = 2.

then in the code in the calculation function there needs to be added the following:

function calculations(input)
   -- split the input into operations
   --[[ use a loop to make sure the calculation is completed in its entirety such 
   as 1+3+1+4 should be calculated like so 1+3 = a, a+1 = b, b+4 = answer]]--

so how can I automate it? so that it understands what to add to the function, not to mention, can you even add code to a script?!

1 Like

Do you want to take a string input like “1+1+4” and get back the results? In that case you can use loadstring but be careful when using it. If you allow players to make inputs then you need to make sure the input is only math, as it runs code that you input.
To use it you can simply do this

local function calculations(input)
	local eval, err = loadstring("return " .. input) -- add return so it returns the results
	if (not eval) then
		warn("error on math evaluation:", err)
		return -- to stop the rest of the function
	return eval() --[[ loadstring returns a function with the code you gave it
	in this case eval would be the same as this function
		return 1 + 1 + 4

but do be very careful when using loadstring as it opens up vulnerabilities to your game