我希望我的C++應用程序的用戶能夠提供匿名函數來執行工作的小塊。如何在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_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的功能,我認爲我的「不太可怕」的破解是唯一的出路。 – 2011-01-31 11:11:25