和我一起写lua - Hello world

lua是非常简单的脚本语言,我们以一个简单的例子开始(假设文件名字为my.lua)


  1. print("Hello world")
具体执行时,在命令行运行:lua my.lua
结果为:
$ lua my.lua 
Hello world

另外,也可以在C语言中调用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 main(int argc, const char *argv[])
  11. {
  12.     if(argc != 2)
  13.     {
  14.         return 1;
  15.     }
  16.     lua_State *= luaL_newstate(); /* Create new lua state variable */

  17.     /* Load Lua libraries, otherwise, the lua function in *.lua will be nil */
  18.     luaL_openlibs(L); 

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

  21.     if( lua_pcall(L,0,0,0) ) /* Run the loaded lua file */
  22.         bail(L, "lua_pcall() failed"); 
  23.     lua_close(L);                 /* Close the lua state variable */    

  24.     return 0;
  25. }
编译:
$ gcc -g ./test_lua.c -llua 
执行:
$ ./a.out my.lua
Hello world

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值