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

use the contents of a var as a var?

Started by etopsirhc, 02 February 2013 - 06:45 AM
etopsirhc #1
Posted 02 February 2013 - 07:45 AM
essentially what i want to do is be be able to call a function with a string that is the variable name i want to use.
i'm doing it this way as the string will be grabbed from args ={ … }

a = 1
function f(var)
  --some how print 1 instead of a
end
f("a")

if at all possible i'd also prefer not to have to set it up as a dictionary
Kingdaro #2
Posted 02 February 2013 - 08:02 AM
In this case, when you define a variable, it's stored in the global "environment", which is basically where all of your variables, tables, functions, etc. are all kept. You can get this environment using _G or getfenv(), the latter is recommended.

a = 1
function f(var)
  local env = getfenv()
  print(env[var])
end
f('a')

However this is usually a more hacky way of doing things, and only works with global variables (not ones defined with "local"). It'd be way easier and more practical to store your variables in a table.

vars = {
  a = 1
}

function f(var)
  print(vars[var])
end

f('a')

In the above example, when f is called with 'a', the function f is doing this:

print(vars['a'])
etopsirhc #3
Posted 02 February 2013 - 08:05 AM
ok , seems simple enough , =D thanks