和我一起写lua - C调用lua函数

在C语言中,可以通过调用lua_register或者luaL_newlib将C函数注册到lua环境,供lua脚本使用。同样道理,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 *= 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

转载于:https://www.cnblogs.com/hanhuilee/archive/2013/01/13/5221382.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值