52 posts
Posted 27 June 2013 - 04:22 PM
I want to know what does setFenv, getFenv, loadString does. I have read the lua wiki but it does not help me one bit.
1583 posts
Location
Germany
Posted 27 June 2013 - 05:06 PM
setfenv:
Spoiler
It allows you to set a function environment.
That means that all global variables defined in the function are saved in your environment. The standard environment is _G.
Example code:
local env = {}
local function cake()
myCake = "yummy"
end
setfenv(env, cake)
cake()
print(env.myCake) --returns "yummy"
Summary:
An environment is a table which contains the variables of a function.
The standard environment is _G.
You set a environment with setfenv(table, functionWithoutBrackets).
52 posts
Posted 27 June 2013 - 05:15 PM
setfenv:
Spoiler
It allows you to set a function environment.
That means that all global variables defined in the function are saved in your environment. The standard environment is _G.
Example code:
local env = {}
local function cake()
myCake = "yummy"
end
setfenv(env, cake)
cake()
print(env.myCake) --returns "yummy"
Summary:
An environment is a table which contains the variables of a function.
The standard environment is _G.
You set a environment with setfenv(table, functionWithoutBrackets).
Thx that helps me a lot but can you explain to me what is getFenv as well?
871 posts
Posted 27 June 2013 - 05:30 PM
getfenv gets a function's environment. I'd've thought that was obvious from the explanation of setfenv…
1583 posts
Location
Germany
Posted 27 June 2013 - 05:32 PM
Yea, I'm not sure if my explaination of getfenv is right but here is it:
Spoiler
getfenv returns the current function environment.
You can use it in many things, for exampl, you want a table which has access to the current environment, and It own variables:
local allVars = {}
setmetatable(allVars, {__index = getfenv())
now the table allVars has access to all variables in the current environment.EDIT:
Damn ninjas :D/>
871 posts
Posted 27 June 2013 - 05:38 PM
:ninja:
To explain a bit more, getfenv() with no arguments gets the current function environment, i.e., what your current function or program is running in. getfenv(myfunc) returns the function environment of the specified function. And getfenv(#), where # is an integer, can be used to get the function environment of parent scopes. The applications of the last are a bit obscure, most frequently you'll want either getfenv() to get the current environment, or getfenv(myfunc) to get the environment of a specific function.
73 posts
Location
Yes
Posted 27 June 2013 - 05:45 PM
loadstring takes a string and tries to load it as lua code. If it works with no errors, it returns a function that does the code you gave it, otherwise it returns nil and an error message
For example,
func = loadstring("print('Hello World!')")
func()
will print 'Hello World!'
loadstring("print('Hello World!'")
would return nil and "lua: 1: [string "string"]: 1: ')' expected" because it's missing the ending )