• 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}


     

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    关闭。没意思
    2015年8月7日15:18:54工作
    2015年8月4日11:43:00工作内容
    博客功能的转变
    php小知识。
    来杭州的工作一览
    开发一款桌面程序。文件转换器
    解决一个题目。关于结构体与链表的操作
    批量检查APK是否具有指定的权限。
    Skynet Pomelo Erlang Elixir 的认识
  • 原文地址:https://www.cnblogs.com/ggzone/p/4786414.html
Copyright © 2020-2023  润新知