C++代码:
// LuaAndC.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <string.h> using namespace std; extern "C" { #include "lua.h" #include "lauxlib.h" #include "lualib.h" } int _tmain(int argc, _TCHAR* argv[]) { //1.创建一个state lua_State *L = luaL_newstate(); luaL_openlibs(L); luaL_dofile(L,"Hello.lua"); //运行脚本 string strScript="print("Hello World From Script!")"; luaL_dostring(L,strScript.c_str(),"MyScript"); //压栈 lua_pushstring(L,"Hunter"); lua_pop(L,1); //获取lua的全局变量 lua_getglobal(L,"str"); //会将lua全局变量压入栈 if(lua_isstring(L,1)) { cout<<lua_tostring(L,1)<<endl;//不弹出栈 } lua_pop(L,1); //准备lua全局函数的栈环境,参数是自左向右依次压栈 lua_getglobal(L,"sayHello"); lua_pushstring(L,"Hunter"); lua_pushstring(L,"18"); //Lua调用函数时,会自动将压入的参数弹出栈,只有返回值在栈中 lua_call(L,2,2); //获取lua函数执行返回值,最后压入栈的返回值在栈顶 cout<<lua_tostring(L,-2)<<endl; cout<<lua_tonumber(L,-1)<<endl; lua_pop(L,2); //4.关闭state lua_close(L); int i; cin>>i; return 0 ; }
Lua代码:
function sayHello(strName,iAge) print("Hello World "..str.." Age "..iAge) return "x"..str,iAge+2 end str="Hello"
版权声明:本文为博主原创文章,未经博主允许不得转载。