Jump to content

How to make a variable name another variable?

3 replies to this topic

#1 gknova61

  • Members
  • 74 posts

Posted 15 January 2013 - 05:06 PM

function varTest(varname)
varname = peripheral.wrap("left")
Basically, I wana make it so the varname is just a string that's the name of a variable like so it can assign a variable name based on the varname you pass to the function

#2 remiX

  • Members
  • 2,076 posts
  • LocationSouth Africa

Posted 15 January 2013 - 05:18 PM

Try using return:

function varTest(side)
  return peripheral.wrap(side)

monitor = varTest("left")

-- but that's the same as:

varTest = peripheral.wrap
-- and then wrapping it, but just with a new function name

monitor = varTest("left")

I don't know for sure but the way you're trying to do, won't work

#3 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 15 January 2013 - 05:51 PM

View PostremiX, on 15 January 2013 - 05:18 PM, said:

I don't know for sure but the way you're trying to do, won't work
Syntactically what he is doing is correct... he is just overriding the value in varname to be the wrap object.

#4 ChunLing

  • Members
  • 2,027 posts

Posted 15 January 2013 - 06:04 PM

You can use a string or number held in one variable to index the contents of a table...and that includes the table holding the current environment (though that is a bit troublesome).

The basic form would be like this:
tbl = {}
function varTest(varname)
tbl[varname] = peripheral.wrap("left")
By calling this, you will assign the result of peripheral.wrap("left") to the index of tbl you passed as an argument to varTest. You can also get the environment table, and insert the index into that. But I do not recommend doing so.

1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users