Chinaunix首页 | 论坛 | 博客
  • 博客访问: 529075
  • 博文数量: 102
  • 博客积分: 2146
  • 博客等级: 大尉
  • 技术积分: 1146
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-09 17:32
文章分类

全部博文(102)

文章存档

2015年(14)

2014年(24)

2013年(5)

2012年(30)

2011年(16)

2010年(13)

分类: C/C++

2015-09-16 12:00:53

1:上table,保存为hello.lua

点击(此处)折叠或打开

  1. tbl = {name = "sky", fullname = "pl", id = 20151223} 
  2. str = "hello world"
2:上C代码

点击(此处)折叠或打开

  1. #include <iostream>
  2. #include <string.h>
  3. using namespace std;

  4. extern "C"
  5. {
  6. #include "lua.h"
  7. #include "lauxlib.h"
  8. #include "lualib.h"
  9. }
  10. void main()
  11. {
  12.     //1.创建一个state
  13.     lua_State *L = luaL_newstate();
  14.     if (L == NULL)
  15.     {
  16.         cout << "New state fail";
  17.         return;
  18.     }

  19.     // 运行脚本
  20.     luaL_dofile(L, "hello.lua");
  21.     // 获得脚本中名为str的全局变量
  22.     lua_getglobal(L, "str");
  23.     // 判断栈顶获取的变量是不是字符串,是就打印出来
  24.     if (lua_isstring(L, -1))
  25.     {
  26.         string str = lua_tostring(L, -1);
  27.         cout << str.c_str() << endl;
  28.     }
  29.     // 获取脚本中的名为tbl的表
  30.     lua_getglobal(L, "tbl");
  31.     // 判断栈顶获取的变量是不是表
  32.     if (lua_istable(L, -1))
  33.     {
  34.         // 此时表放在栈2位置,所以这里将2位置的变量作Table解析,并取出其中的“name”键的值压入交互栈顶
  35.         lua_getfield(L, 2, "name");    
  36.         string str = lua_tostring(L, -1);
  37.         cout << str.c_str() << endl;
  38.         // 此时表放在栈2位置,所以这里将2位置的变量作Table解析,并取出其中的“fullname”键的值压入交互栈顶
  39.         lua_getfield(L, 2, "fullname");
  40.         str = lua_tostring(L, -1);
  41.         cout << str.c_str() << endl;
  42.         // 此时表放在栈2位置,所以这里将2位置的变量作Table解析,并取出其中的“id”键的值压入交互栈顶
  43.         lua_getfield(L, 2, "id");
  44.         int num = lua_tonumber(L, -1);
  45.         cout << "id is " << num << endl;
  46.     }
  47.     // 此时若打印栈顶位置,应该为5,依次是1:str, 2:tbl, 3:name, 4:fullname, 5:id
  48.     cout << lua_gettop(L) << endl;
  49.     //4.关闭state
  50.     lua_close(L);
  51.     return;
  52. }


阅读(2333) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~