cc代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "lua.hpp"
#include "lauxlib.h"
#include "lualib.h"
static void stackDump(lua_State* L)
{
static int count = 0;
printf("begin dump lua stack:%d\n", count);
int top = lua_gettop(L);
for (int i = top; i > 0; --i)
{
int t = lua_type(L, i);
switch (t)
{
case LUA_TSTRING:
printf("%s\n", lua_tostring(L, i));
break;
case LUA_TBOOLEAN:
printf(lua_toboolean(L, i) ? "true\n" : "false\n");
break;
case LUA_TNUMBER:
printf("%g\n", lua_tonumber(L, i));
break;
default:
printf("%s\n", lua_typename(L, t));
break;
}
}
++count;
}
int main()
{
lua_State* L = luaL_newstate(); /* create state */
if (L == NULL) {
printf("lua state build error.\n");
return 1;
}
luaL_openlibs(L);
luaL_dofile(L, "test.lua");
lua_getglobal(L, "age"); // 将lua中全局变量存放到lua栈顶中(这个栈是C与lua交互的通道)
lua_getglobal(L, "name");
stackDump(L);
std::cin.get();
lua_close(L);
return 0;
}
lua代码:
print("print from test lua.")
name = "linxing"
age = 19