和我一起写lua - 使用C扩展lua

在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 *= 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

转载于:https://www.cnblogs.com/hanhuilee/archive/2013/01/12/5221385.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值