和我一起写lua - Hello world

4765阅读 0评论2013-01-11 hanhuili
分类:Python/Ruby

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

上一篇:python radix算法实现
下一篇:和我一起写lua - 使用C扩展lua