debug/getlocal

From Garry's Mod
(Difference between revisions)
Jump to: navigation, search
m (Also menu state)
(Warning about tailcall optimized function return)
 
Line 1: Line 1:
 
{{Func
 
{{Func
 
|Description=Gets the name and value of a local variable indexed from the level
 
|Description=Gets the name and value of a local variable indexed from the level
 +
{{Warning|When a function has a tailcall return, you cannot access the locals of this function}}
 
|Realm=Shared and Menu
 
|Realm=Shared and Menu
 
|IsClass=No
 
|IsClass=No

Latest revision as of 13:24, 14 November 2019

 debug.getlocal( )

Contents

Description

Gets the name and value of a local variable indexed from the level

WARNING

When a function has a tailcall return, you cannot access the locals of this function

Arguments

thread thread=Current thread

The thread

Arguments

number level

The level above the thread. 0 = the function that was called (most always this function)'s arguments

1 = the thread that had called this function.

2 = the thread that had called the function that started the thread that called this function.

A function defined in Lua can also be passed as the level. The index will specify the parameter's name to be returned (a parameter will have a value of nil).

Arguments

number index

The variable's index you want to get.

1 = the first local defined in the thread

2 = the second local defined in the thread

etc...

Returns

string

The name of the variable

Sometimes this will be "(*temporary)" if the local variable had no name.

NOTE

Variables with names starting with ( are internal variables.

Returns

any

The value of the local variable.

Examples

Example

Gets all the local variables of the current thread and stores them in a table.

local name, value;
local NIL = {} -- to represent nil variables
local locals = {}
local i = 1
while( true ) do
    name, value = debug.getlocal( 1, i )
    if ( name == nil ) then break end
    locals[ name ] = value == nil and NIL or value
	i = i + 1
end

for k,v in pairs( locals ) do 
	print( k, v )
end

Output:

locals	table: 0x274a8dc0
value	table: 0x274a8d98
NIL	table: 0x274a8d98
name	table: 0x274a8d98
i	5

Examples

Example

Prints the parameter names for hook.Add

local print = print
local getlocal = debug.getlocal

local function PrintFunctionParameters(func)
	local k = 2
	local param = getlocal(func, 1)
	while param ~= nil do
		print(param)
		param = getlocal(func, k)
		k = k + 1
	end
end

PrintFunctionParameters(hook.Add)

Output:

event_name
name
func
Personal tools
Navigation