打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

分类: Python/Ruby

原文地址:和我一起写lua - C调用lua函数 作者:hanhuili

在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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Lua 教程 | 菜鸟教程
(1)LUA源码阅读(四)
【精髓】明天就要面试客户端岗位,面对主管的专业提问,我真的好慌!
漫谈C语言及如何学习C语言
Lua脚本语法说明(修订) - 沐枫小筑
采访Lua发明人的一篇文章_Lua_程序语言
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服