--lua文件为a.lua
myname = "chanhui"
//C++代码
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
const char *peizhi = "a.lua";
lua_State *L = luaL_newstate();
luaL_openlibs(L);
//加载lua文件并执行lua文件
if (luaL_loadfile(L, peizhi) || lua_pcall(L, 0, 0, 0))
{
printf("error..........\n");
exit(0);
}
lua_getglobal(L, "myname");
const char *name = lua_tostring(L, -1);
printf("name = %s\n", name);
lua_pop(L, -1);
lua_pushstring(L, "silence");
lua_setglobal(L, "myname");
lua_getglobal(L, "myname");
name = lua_tostring(L, -1);
printf("name = %s\n", name);
lua_pop(L, -1);
return 0;
}
//g++ a.c -llua5.1