如何在Lua中加载未命名的函数?

Mic*_*son 6 lua

我希望我的C++应用程序的用户能够提供匿名函数来执行小块工作.

像这样的小碎片是理想的.

function(arg) return arg*5 end
Run Code Online (Sandbox Code Playgroud)

现在,我希望能够为我的C代码编写简单的内容,

// 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);
Run Code Online (Sandbox Code Playgroud)

但是我不认为lua_loadstring会做"正确的事情".

我是否留下了对我来说像一个可怕的黑客的感觉?

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);
Run Code Online (Sandbox Code Playgroud)

有更好的解决方案吗?

Mic*_*man 7

如果您需要访问参数,您编写的方式是正确的.lua_loadstring返回一个表示您正在编译的块/代码的函数.如果你想从代码中实际获得一个函数,你就必须return这样做.我也做了这个(在Lua)的小"表达评估员",我不认为这是一个"可怕的黑客":)

如果你只需要一些回调,没有任何参数,你可以直接编写代码并使用返回的函数lua_tostring.您甚至可以将参数传递给此块,它可以作为...表达式访问.然后你可以得到如下参数:

local arg1, arg2 = ...
-- rest of code
Run Code Online (Sandbox Code Playgroud)

你决定什么对你更好 - 你的库代码库中的"丑陋代码",或Lua函数中的"丑陋代码".