你可以在主机程序中向脚本提供你自定的api,供脚本调用。
Lua定义了一种类型:lua_CFunction,这是一个函数指针,它的原型是:
typedef int (*lua_CFunction) (lua_State *L);
这意味着只有这种类型的函数才能向Lua注册。
首先,我们定义一个函数
int foo(lua_State *L)
{
//首先取出脚本执行这个函数时压入栈的参数
//假设这个函数提供一个参数,有两个返回值
//get the first parameter
const char *par = lua_tostring(L, -1);
printf("%s/n", par);
//push the first result
lua_pushnumber(L, 100);
//push the second result
lua_pushnumber(L, 200);
//return 2 result
return 2;
}
我们可以在脚本中这样调用这个函数
r1, r2 = foo("hello")
print(r1..r2)
完整的测试代码如下:
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int foo(lua_State *L)
{
//首先取出脚本执行这个函数时压入栈的参数
//假设这个函数提供一个参数,有两个返回值
//get the first parameter
const char *par = lua_tostring(L, -1);
printf("%s/n", par);
//push the first result
lua_pushnumber(L, 100);
//push the second result
lua_pushnumber(L, 200);
//return 2 result
return 2;
}
int main(int argc, char *argv[])
{
lua_State *L = lua_open();
luaopen_base(L);
luaopen_io(L);
//此处原先少了这一行
//感谢freerpg@sina.com提醒
lua_register(L, "foo", foo);
const char *buf = "r1, r2 = foo("hello") print(r1..r2)";
lua_dostring(L, buf);
lua_close(L);
return 0;
}
程序输出:
hello
100200
博客介绍了在主机程序中向Lua脚本提供自定义API的方法。定义了lua_CFunction类型,只有该类型函数才能向Lua注册。给出了示例函数foo及在脚本中的调用方式,还展示了完整测试代码,程序最终输出hello100200。
:扩展Lua&spm=1001.2101.3001.5002&articleId=253740&d=1&t=3&u=4e19926f79fa41e6b005091748f9904f)
1万+

被折叠的 条评论
为什么被折叠?



