Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26147
  • 博文数量: 6
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 12
  • 用 户 组: 普通用户
  • 注册时间: 2013-04-27 20:03
文章分类
文章存档

2013年(6)

我的朋友

分类: Python/Ruby

2013-04-27 20:14:24

在C语言中,可以通过调用lua_register或者luaL_newlib将C函数注册到lua环境,供lua脚本使用(请参考[1], [2],[3],[4])。同样道理,C语言也可以通过lua API调用lua函数。具体例子:

点击(此处)折叠或打开

  1. #include <lua.h>
  2. #include <lauxlib.h>

  3. #include <stdlib.h> /* For function exit() */
  4. #include <stdio.h> /* For input/output */

  5. void bail(lua_State *L, char *msg){
  6.     fprintf(stderr, "\nFATAL ERROR:\n %s: %s\n\n",
  7.         msg, lua_tostring(L, -1));
  8.     exit(1);
  9. }
  10. void lua_print(lua_State *L, double x) { /* call lua print */
  11.     /* push functions and arguments */
  12.     lua_getglobal(L, "print"); /* function to be called */
  13.     lua_pushnumber(L, x); /* push 1st argument */
  14.     /* do the call (1 arguments, 1 result) */
  15.     if (lua_pcall(L, 1, 0, 0) != 0)
  16.     {
  17.         return 2;
  18.     }
  19.     return;
  20. }
  21. int main(int argc, const char *argv[])
  22. {
  23.     lua_State *L = luaL_newstate(); /* Create new lua state variable */
  24.     /* Load Lua libraries, otherwise, the lua function in *.lua will be nil */
  25.     luaL_openlibs(L);
  26.     lua_print(L,1);    
  27.     lua_close(L);                   /* Close the lua state variable */    

  28.     return 0;
  29. }
编译:
gcc -g -o test_call_lua test_call_lua.c -llua

执行:
$ ./test_call_lua
1


阅读(1690) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~