zoukankan      html  css  js  c++  java
  • C++对Lua中table进行读取、修改和创建

    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");
    	
    	//获取table的值
    	lua_getglobal(L,"str");
    
    	//会将get的对应项压到栈顶
    	lua_getfield(L,1,"name");
    	lua_getfield(L,1,"age");
    
    	if(lua_isstring(L,2))
    	{
    		cout<<"name= "<<lua_tostring(L,-2)<<endl;
    	}
    	if(lua_isnumber(L,3))
    	{
    		cout<<"age= "<<lua_tonumber(L,-1)<<endl;
    	}
    	lua_pop(L,2);
    
    	//修改table的项
    	lua_pushfstring(L,"So so");//改完弹出
    	lua_setfield(L,1,"name");
    	lua_getfield(L,1,"name");
    	if(lua_isstring(L,2))
    	{
    		cout<<"name1= "<<lua_tostring(L,2)<<endl;
    	}
    	lua_pop(L,2);
    
    	//新建table
    	lua_newtable(L); //压栈
    	lua_pushnumber(L,11);
    	lua_pushstring(L,"New");
    	lua_setfield(L,1,"name");
    	lua_setfield(L,1,"age");
    	lua_getfield(L,1,"name");
    	lua_getfield(L,1,"age");
    	if(lua_isstring(L,2))
    	{
    		cout<<"name= "<<lua_tostring(L,2)<<endl;
    	}
    	if(lua_isnumber(L,3))
    	{
    		cout<<"age= "<<lua_tonumber(L,3)<<endl;
    	}
    
    	lua_pop(L,3);
    
        //关闭state  
        lua_close(L);  
    	
    	int i;
    	cin>>i;
        return 0 ;  
    }
    
    


     

    Lua代码:

    str={name="Hunter",age=18}


     

  • 相关阅读:
    最简单跨平台的日志库
    linux文件锁
    Linux 获取屏幕分辨率与窗口行列数(c/c++)
    linux 信号机制
    记一次函数异常(getopt_long)
    程序单实例运行
    简单地 Makefile 书写
    学习go的一些笔记
    20200930 10. Netty 核心源码剖析
    20200930 9. TCP 粘包和拆包 及解决方案
  • 原文地址:https://www.cnblogs.com/ggzone/p/10121267.html
Copyright © 2011-2022 走看看