6

I want users of my C++ application to be able to provide anonymous functions to perform small chunks of work.

Small fragments like this would be ideal.

function(arg) return arg*5 end

Now I'd like to be able to write something as simple as this for my C code,

// Push the function onto the lua stack
lua_xxx(L, "function(arg) return arg*5 end" )
// Store it away for later
int reg_index = luaL_ref(L, LUA_REGISTRY_INDEX);

However I dont think lua_loadstring will do "the right thing".

Am I left with what feels to me like a horrible hack?

void push_lua_function_from_string( lua_State * L, std::string code )
{
   // Wrap our string so that we can get something useful for luaL_loadstring
   std::string wrapped_code = "return "+code;
   luaL_loadstring(L, wrapped_code.c_str());
   lua_pcall( L, 0, 1, 0 );
}

push_lua_function_from_string(L, "function(arg) return arg*5 end" );
int reg_index = luaL_ref(L, LUA_REGISTRY_INDEX);

Is there a better solution?

2 Answers 2

7

If you need access to parameters, the way you have written is correct. lua_loadstring returns a function that represents the chunk/code you are compiling. If you want to actually get a function back from the code, you have to return it. I also do this (in Lua) for little "expression evaluators", and I don't consider it a "horrible hack" :)

If you only need some callbacks, without any parameters, you can directly write the code and use the function returned by lua_tostring. You can even pass parameters to this chunk, it will be accessible as the ... expression. Then you can get the parameters as:

local arg1, arg2 = ...
-- rest of code

You decide what is better for you - "ugly code" inside your library codebase, or "ugly code" in your Lua functions.

Sign up to request clarification or add additional context in comments.

2 Comments

I've also decided its not quite as hacky as my gut feel suggested. And since end users are going to be writing the lua functions, I think that my "not-so-horrible" hack is the only way to go.
Michal has it right. The "chunk" can accept arguments but needs the return.
3

Have a look at my ae. It caches functions from expressions so you can simply say ae_eval("a*x^2+b*x+c") and it'll only compile it once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.