Chinaunix首页 | 论坛 | 博客
  • 博客访问: 253478
  • 博文数量: 60
  • 博客积分: 1222
  • 博客等级: 少尉
  • 技术积分: 585
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-16 17:28
个人简介

从学通信的博士到从事IT行业的工程师 从原华为项目经理,到现任职公司架构师

文章分类

全部博文(60)

文章存档

2013年(18)

2012年(42)

我的朋友

分类: Python/Ruby

2013-01-11 23:31:23

在C文件中,可以通过调用lua_register函数注册新的可以在lua脚本中使用的函数。
具体例子(test_lua.c)如下所示:

点击(此处)折叠或打开

  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. int lua_func_from_c_func(lua_State *L)
  11. {
  12.     printf("This is C\n");
  13.     return 0;
  14. }
  15. int main(int argc, const char *argv[])
  16. {
  17.     if(argc != 2)
  18.     {
  19.         return 1;
  20.     }
  21.     lua_State *L = luaL_newstate(); /* Create new lua state variable */
  22.     
  23.     /* Load Lua libraries, otherwise, the lua function in *.lua will be nil */
  24.     luaL_openlibs(L);
  25.     
  26.     /* register new lua function in C */
  27.     lua_register(L, "lua_func_from_c", lua_func_from_c_func);

  28.     if( luaL_loadfile(L,argv[1]) ) /* Only load the lua script file */
  29.         bail(L, "luaL_loadfile() failed");

  30.     if( lua_pcall(L,0,0,0) ) /* Run the loaded lua file */
  31.         bail(L, "lua_pcall() failed");
  32.     lua_close(L);                 /* Close the lua state variable */    

  33.     return 0;
  34. }
调用lua_register后,第二个参数lua_func_from_c可以在随后调用的lua脚本中作为一个lua函数使用。

具体脚本如下所示:

点击(此处)折叠或打开

  1. print("Hello world")
  2. lua_func_from_c()
执行结果:
$ ./a.out my.lua 
Hello world
This is C


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