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

How to make a variable name another variable?

Started by gknova61, 15 January 2013 - 04:06 PM
gknova61 #1
Posted 15 January 2013 - 05:06 PM
Example:
function varTest(varname)
varname = peripheral.wrap("left")
end
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
remiX #2
Posted 15 January 2013 - 05:18 PM
Try using return:


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

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
theoriginalbit #3
Posted 15 January 2013 - 05:51 PM
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.
ChunLing #4
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")
end
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.