Jump to content




use the contents of a var as a var?


  • You cannot reply to this topic
2 replies to this topic

#1 etopsirhc

  • Members
  • 122 posts

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

#2 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

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'])


#3 etopsirhc

  • Members
  • 122 posts

Posted 02 February 2013 - 08:05 AM

ok , seems simple enough , =D thanks





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users