一个导出lua堆栈内数据的例子,可以用来辅助开发

今天为了让脚本程序调试方便,给他们写了一个导出lua堆栈的辅助函数,用起来挺方便的,可以导出常用的类型,包括表,和表的嵌套。

//@generated "UML to C++ (com.ibm.xtools.transform.uml2.cpp.CPPTransformation)"
a_string gluon::CStackDumper::Dump(CScriptDevice* device, int offset)
{
	//TODO Auto-generated method stub
	a_string result;
	if( device )
	{
		int size = lua_gettop( device );
		if( offset <= size )
		{
			char msg[64];
			int type = lua_type( device, offset );

			switch( type )
			{
			case LUA_TBOOLEAN:
				{
					lua_toboolean( device, offset ) ? 
						result += "true":
						result += "false";
				}
				break;
			case LUA_TNUMBER:
				{
					if( lua_isinteger(device, offset) )
					{
						I64 value = lua_tointeger( device, offset );
						sprintf( msg, "%lli", value );
						result += msg;
					}
					else
					{
						double value = lua_tonumber( device, offset );
						sprintf( msg, "%f", value );
						result += msg;
					}
				}
				break;
			case LUA_TSTRING:
				{
					result +="\"";
					const char * ptr = lua_tostring( device, offset );
					if( ptr ) {
						result += ptr;
					}
					result +="\"";
				}
				break;
			case LUA_TTABLE:
				{
					bool first = true;
					result += "{ ";

					lua_checkstack( device, 1 );
					lua_pushnil   ( device );

					while( lua_next(device, offset) )
					{
						if( first == false ) {
							result += ", ";
						}
						
						result += Dump( device, size + 1 );
						result += ": ";
						result += Dump( device, size + 2 );
						lua_pop( device, 1 );

						first = false;
					}

					result += " }";

					// lua_next如果发现没有下一个之后,会自动将栈顶弹出
					// 无需再处理
				}
				break;
			case LUA_TNONE:
			case LUA_TNIL:
			case LUA_TFUNCTION:
			case LUA_TTHREAD:
			case LUA_NUMTAGS:
			case LUA_TUSERDATA:
			case LUA_TLIGHTUSERDATA:
				{
					const char * ptr =
						lua_typename( device, type );
					if( ptr ) {
						result += ptr;
					}
				}
				break;
			}
		}
	}
	return result;
}

//@generated "UML to C++ (com.ibm.xtools.transform.uml2.cpp.CPPTransformation)"
a_string gluon::CStackDumper::Dump(CScriptDevice* device)
{
	//TODO Auto-generated method stub
	a_string result;
	if( device )
	{
		char msg[16];
		int size = lua_gettop( device );
		for( int i = 1; i <= size; ++i )
		{
			sprintf( msg, "[%02d] ", i );
			result += msg;
			result += Dump( device, i );
			result += ";\n";
		}
	}
	return result;
}

上一篇:fishDispose.lua.txt


下一篇:阅读《Lua程序设计(第4版)》---0