我在.lua文件中声明并初始化了一些函数。然后,当我收到信号时,我读取string_t变量,其中包含要从文件调用的函数名称。问题是我不知道如何按功能将函数推送到堆栈或调用它。
例如:
test.lua
function iLoveVodka()
--some text
end
function iLoveFish()
--another text
end
C档案:
string_t a = "iLoveVodka()"
如何仅通过名称来调用C / C ++代码iLoveVodka()
中的函数?
答案 0 :(得分:1)
以下是一些做两件事的示例代码:
iLoveVodka()
,如果可以找到它。你应该能够轻松地构建它:
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[])
{
lua_State *l = luaL_newstate ();
luaL_openlibs (l);
int error = luaL_dofile (l, "test.lua");
if (error)
{
printf( "Error loading test.lua: %s\n",luaL_checkstring (l, -1) );
exit(1);
}
/**
* Get the function and call it
*/
lua_getglobal(l, "iLoveVodka");
if ( lua_isnil(l,-1) )
{
printf("Failed to find global function iLoveVodka\n" );
exit(1);
}
lua_pcall(l,0,0,0);
/**
* Cleanup.
*/
lua_close (l);
return 0;
}
这可以像这样编译:
gcc -O -o test `pkg-config --libs --cflags lua5.1` test.c
只需在iLoveVodka()
中定义test.lua
功能,就可以了。