lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Karsten Schulz once stated:
> Hi together,
> 
> i extract in a debug -view the content of local variables to show them in a 
> editor.
> 
> how i become the content od a global variable from them name in a 
> scriptline ?

  If you have the name of a global, then lua_getglobal() will push the value
onto the Lua stack, which (using your code as a reference) might look like:

	/*------------------------------------------------------------------
	; Have Lua to the heavy work of converting the type to a string for
	; us.  To do that, we obtain the Lua function tostring() on the
	; stack, then obtain the value of the global we have the name for. 
	; Before we call tostring() though, we get the original type of the
	; variable.  Call tostring(), and format our output.
	;------------------------------------------------------------------*/

	lua_getglobal(lua,"tostring");
	lua_getglobal(lua,name);
	strtype = luaL_typename(lua,-1);
	lua_call(lua,1,1);
	varval.Format("%s=%s %s",name,lua_tostring(lua,-1),strtype);
	lua_pop(lua,1);

  For a list of all globals, iterate through the global environment.  In Lua
5.2, you do something like:

	lua_pushnil(lua);	/* initialize first key */
	while(lua_next(lua,LUA_RIDX_GLOBALS) != 0)
	{
	  const char *name = lua_tostring(L,-2);
	  lua_getglobal(lua,"tostring"); /* use tostring() to do conversion for us */
	  lua_pushvalue(lua,-2);	 /* get value to convert */
	  lua_call(lua,1,1);		 /* do conversion */

	  /*----------------------------------------------------------------
	  ; since we already have the original value on the stack, we don't
	  ; need to obtain the typename before the call.  The Lua stack at
	  ; this points looks like:
	  ;
	  ;	-3 name (key for lua_next())
	  ;     -2 value
	  ;     -1 value as string
	  ;
	  ; We format the data, then pop off the two values, leaving the key
	  ; for the next call to lua_next().
	  ;---------------------------------------------------------------*/

	  varval.Format("%s=%s %s",name,lua_tostring(lua,-1),luaL_typename(lua,-2));
	  lua_pop(lua,2);
	}

  Now, if you are asking how to get a list of globals used in a function,
I'm afraid that requires a bit more work (like, parsing and building an AST,
tracking variable usage and if they're global or local---if any of this
doesn't make sense, well ... like I said, it's a bit more work).

  -spc (Merry Christmas!)