G.setfenv

From GMod Wiki

Jump to: navigation, search
Function
Syntax setfenv( function Affected Function : Integer Stack Level , Table Environment )
Where is this used?
Description:
Sets what a function sees as the global environment, or to put it another way, what table the function searches when you call up a global variable.
Returns: function
Part of Library: Global Functions
Realm: NewerShared.png
BBCode Link: [b][url=http://wiki.garrysmod.com/?title=G.setfenv]G.setfenv [img]http://wiki.garrysmod.com/favicon.ico[/img][/url][/b]



Examples

DescriptionA demonstration of the function.
Used onNewerShared.png
Code
 
a = 10				-- A Global Variable
 
setfenv( 1, {GLOBAL = _G} )	-- Set The Environment To An Empty Table ( 1 means the current function on the callstack )
				-- _G is the default Global Environment 
				-- We preserve the ability to call upon it by storing it into 'GLOBAL'
 
print(a)			--> nil, ( because the new environment has no 'a' index this returns nil )
print(GLOBAL.a)			--> 10 , ( 'a' still exists in the old environment, so it can still be referenced this way )
 
-- going backwards...
setfenv(1, GLOBAL)		-- Sets the global environment back to the original one
 
print(a)			--> 10 , ( now we're back in the old environment we can get the value of 'a' as normal )
print(GLOBAL)			--> nil, ( 'GLOBAL' doesn't exist in this environment, so this will return nil )
 
Outputnil, 10.


Additional Notes

See Also

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox