C++ Lua
#include <iostream> #include "D:/Program Files/Lua/include/lua.hpp" #pragma comment(lib, "D:/Program Files/Lua/lib/lua51.lib") using namespace std; int main(int argc, char* argv[]) { //创建Lua运行环境 lua_State* L = luaL_newstate(); if(L == NULL) { cout<<"luaL_newstate() fail!"<<endl; return -1; } //加载Lua基本库 luaL_openlibs(L); //加载Lua脚本 //int ret = luaL_dofile(L, "testlua.lua"); //if(ret != 0) { // cout<<"luaL_dofile() fail!"<<endl; // return -1; //} //加载Lua脚本 int ret = luaL_loadfile(L, "testlua.lua"); if(ret != 0) { cout<<"luaL_loadfile() fail!"<<endl; return -1; } ret = lua_pcall(L, 0, 0, 0); if(ret != 0) { cout<<"lua_pcall() fail!"<<endl; lua_close(L); return -1; } //调用Lua中的函数 lua_getglobal(L, "add"); lua_pushinteger(L, 11) ; lua_pushinteger(L, 12) ; ret = lua_pcall(L, 2, 1, 0); if(ret != 0) { cout<<"lua_pcall() fail!"<<endl; lua_close(L); return -1; } //返回栈顶元素,然后清栈 cout<<"result: "<<lua_tointeger(L, -1); lua_pop(L, 1); //释放Lua运行环境 lua_close(L); return 0; }