zoukankan      html  css  js  c++  java
  • C++获取Lua全局变量和执行Lua多参数多返回值函数

    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"


     

  • 相关阅读:
    【数据大屏设计】有点意思
    MySQL环境搭建
    关于MySQL数据库
    zip-gzip-bzip2_压缩文件
    Linux的链接文件-ln命令
    电脑为什么越用越慢
    按下开机键,计算机背后的故事
    Windows最全快捷键
    环境搭建-VMware安装系统
    wee hours
  • 原文地址:https://www.cnblogs.com/ggzone/p/10121268.html
Copyright © 2011-2022 走看看