LUA脚本调用C函数是非常方便的,需要在C文件里首先实现好C的函数,然后把C函数和lua的调用名注册到一个库里。
下面的例子是lua脚本调用test.output然后会最终调用到C函数Test_output.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ltestlib_c
#define LUA_TEST_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
static int Test_output(lua_State *L)
{
unsigned char output[128];
fputs("enter Test_output",stdout);
int n = lua_gettop(L); /* number of arguments */
//extern int sprintf (char *, const char *, ...);
sprintf(output,"input parameter number is <%d>\n",n);
fputs(output, stdout);
return 1;
}
static const luaL_Reg testlib[] = {
{"output", Test_output},
{NULL, NULL}
};
LUALIB_API int luaopen_test (lua_State *L) {
luaL_register(L, "TEST", testlib);
return 1;
}
static const luaL_Reg lualibs[] = {
{"", luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_DBLIBNAME, luaopen_debug},
{"TEST",luaopen_test},
{NULL, NULL}
};
test.output(1,2,3,4,5,6,7,8,9)