如何在Lua中加载未命名函数? < >我希望我的C++应用程序的用户能够提供匿名函数来执行小的工作组。
像这样的小碎片将是理想的如何在Lua中加载未命名函数? < >我希望我的C++应用程序的用户能够提供匿名函数来执行小的工作组。,lua,Lua,像这样的小碎片将是理想的 function(arg) return arg*5 end 现在我希望能够为我的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); 然而,我认为lua_loadstri
function(arg) return arg*5 end
现在我希望能够为我的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);
然而,我认为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);
有更好的解决方案吗?如果您需要访问参数,那么您编写的方法是正确的
lua_loadstring
返回一个函数,该函数表示正在编译的块/代码。如果要从代码中实际获取函数,必须返回它。我也在(Lua)做一些“表达式计算器”,我不认为它是“可怕的黑客”:
如果您只需要一些回调,而不需要任何参数,那么可以直接编写代码并使用lua\u tostring
返回的函数。您甚至可以将参数传递给该块,它将作为…
表达式进行访问。然后您可以获得如下参数:
local arg1, arg2 = ...
-- rest of code
您可以决定什么对您更有利—库代码库中的“丑陋代码”,或Lua函数中的“丑陋代码”。看看我的。它从表达式中缓存函数,因此您可以简单地说ae_eval(“a*x^2+b*x+c”)
,并且它只编译一次。我还决定它并不像我直觉所暗示的那么粗糙。由于最终用户将要编写lua函数,我认为我的“不那么可怕”的破解是唯一的出路。Michal说得对。“chunk”可以接受参数,但需要返回。