在C语言中,可以通过调用lua_register或者luaL_newlib将C函数注册到lua环境,供lua脚本使用。同样道理,C语言也可以通过lua API调用lua函数。具体例子:
编译:
- #include <lua.h>
- #include <lauxlib.h>
- #include <stdlib.h> /* For function exit() */
- #include <stdio.h> /* For input/output */
- void bail(lua_State *L, char *msg){
- fprintf(stderr, "\nFATAL ERROR:\n %s: %s\n\n",
- msg, lua_tostring(L, -1));
- exit(1);
- }
- void lua_print(lua_State *L, double x) { /* call lua print */
- /* push functions and arguments */
- lua_getglobal(L, "print"); /* function to be called */
- lua_pushnumber(L, x); /* push 1st argument */
- /* do the call (1 arguments, 1 result) */
- if (lua_pcall(L, 1, 0, 0) != 0)
- {
- return 2;
- }
- return;
- }
- int main(int argc, const char *argv[])
- {
- lua_State *L = luaL_newstate(); /* Create new lua state variable */
- /* Load Lua libraries, otherwise, the lua function in *.lua will be nil */
- luaL_openlibs(L);
- lua_print(L,1);
- lua_close(L); /* Close the lua state variable */
- return 0;
- }
gcc -g -o test_call_lua test_call_lua.c -llua
执行:
$ ./test_call_lua
1