如何在Lua中加载一个未命名且未定义的函数?
- 内容介绍
- 文章标签
- 相关推荐
本文共计402个文字,预计阅读时间需要2分钟。
我希望我的C应用程序的用户能够提供匿名功能来执行小块工作。像这样的小片段是理想的。+function(arg) { return arg * 5; } end+ 现在,我希望能够为我编写的C代码编写简单的逻辑,// Push the function onto the
我希望我的C应用程序的用户能够提供匿名功能来执行小块工作.像这样的小碎片是理想的.
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_tostring返回的函数.您甚至可以将参数传递给此块,它可以作为…表达式访问.然后你可以得到如下参数:
local arg1, arg2 = ... -- rest of code
你决定什么对你更好 – 你的库代码库中的“丑陋代码”,或Lua函数中的“丑陋代码”.
本文共计402个文字,预计阅读时间需要2分钟。
我希望我的C应用程序的用户能够提供匿名功能来执行小块工作。像这样的小片段是理想的。+function(arg) { return arg * 5; } end+ 现在,我希望能够为我编写的C代码编写简单的逻辑,// Push the function onto the
我希望我的C应用程序的用户能够提供匿名功能来执行小块工作.像这样的小碎片是理想的.
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_tostring返回的函数.您甚至可以将参数传递给此块,它可以作为…表达式访问.然后你可以得到如下参数:
local arg1, arg2 = ... -- rest of code
你决定什么对你更好 – 你的库代码库中的“丑陋代码”,或Lua函数中的“丑陋代码”.

