Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load an unnamed function in Lua?

Tags:

lua

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?

like image 564
Michael Anderson Avatar asked Jan 28 '11 01:01

Michael Anderson


1 Answers

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.

like image 64
Michal Kottman Avatar answered Sep 18 '22 23:09

Michal Kottman