2
votes

I am trying to create a Lua function "on the fly", from within another function. The new Lua function, to be called "fx", should operate on a scalar variable -- say, x -- and return f_x(x), where f_x(x) could be something such as "x+1" or "x^2". Importantly, the function name "fx" is given (as it will be used, with this name, from within other functions), but its properties -- specifically, whether it returns "x+1" or "x^2" -- should be modifiable dynamically.

Suppose that "x" is the scalar-valued input variable and that "y" is a string that contains an instruction, such as "x+1" or "x^2", that "fx" is supposed to impose on "x". I've naively tried

function make_func (x,y)
   return ( function fx(x) return y end )
end

but that doesn't work.

Any help and guidance will be greatly appreciated!

1
"to be called "fx"" Functions in Lua don't really have names. Your make_func is merely storing the function in a global table entry named "make_func", but the function itself can exist independently of that. So are you trying to make a function that gets stored in a global named "fx", or where exactly do you want to store it?Nicol Bolas
@NicolBolas - My apologies for the unintentional vagueness. I would like to use a global named "fx" for the function name.Mico

1 Answers

4
votes

It's not clear how "fx" is supposed to enter the picture, but if you have a string that contains potentially executable Lua code (a Lua expression which would compile if done so in a context where "x" exists), then this seems to be a simple case of building a string from bits of Lua code and executing it:

function make_func (x, lua_op)
   return dostring("return function(x) return " .. lua_op .. " end")
end

This requires lua_op to store a string which is a legitimate Lua expression.

If you want to store the function in the global variable "fx", you can do that before returning it:

function make_func (x, lua_op)
   fx = dostring("return function(x) return " .. lua_op .. " end")
   return fx
end