This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
oeed's profile picture

List All Variables

Started by oeed, 28 February 2013 - 09:29 PM
oeed #1
Posted 28 February 2013 - 10:29 PM
In a project I am making I need to run an separate Lua file at the same time as the current one. This is working fine using os.run(…). However, I am having a bit of trouble with the environment. I need the separate Lua file to access all the variables and functions in the main file. I could add all of the functions to the environment one by one, but there must be another way.

I've looked at _G but that doesn't seem to work.

For example, the following code list all the standard variables and functions (e.g. 'os', 'math', etc) but not 'aFunction' or 'aVariable'. What can I use to get them.


aVariable = "Hello"


function aFunction (message)
	print(message)
end

for key, value in pairs(_G) do
	print(key)
	print(value)
end

If you have a better idea on how to add all the functions to the environment please suggest it.
GopherAtl #2
Posted 01 March 2013 - 12:22 AM
getfenv() returns the current function environment, which will contain all non-local variables and functions you've declared in your program.
KaoS #3
Posted 01 March 2013 - 01:47 AM
in you current file use


os.run(getfenv(),"thesecondfile")

and the second file will have access to all GLOBAL variables from the first file. there is no way to access local variables in a different file
oeed #4
Posted 01 March 2013 - 01:21 PM
in you current file use


os.run(getfenv(),"thesecondfile")

and the second file will have access to all GLOBAL variables from the first file. there is no way to access local variables in a different file


getfenv() returns the current function environment, which will contain all non-local variables and functions you've declared in your program.

Thanks both of you, worked a charm.