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

Setting variables in a method

Started by MatthewGB, 26 May 2014 - 02:23 AM
MatthewGB #1
Posted 26 May 2014 - 04:23 AM
I need to chage a variable from within the method where the variable is one of the method's parameters.

testvar = 1
function sv(var, setto) -- set variable
 var = setto
end
sv(testvar, 2)
print(testvar)
[EndOfCode]
It prints 1. How do I change the variable?
KingofGamesYami #2
Posted 26 May 2014 - 04:37 AM
What you are doing there is setting 1 to 2 lol. sv(testvar, 2) translates to sv(1, 2) in lua.
Why not just do this:

testvar = 1
testvar = 2
print(testvar)

Of course, you should use local, but don't use it more than once

local testvar = 1
print(testvar)
testvar = 2 --#will not affect global testvar, instead changes the local one
print(testvar)
Edited on 26 May 2014 - 02:38 AM
MatthewGB #3
Posted 26 May 2014 - 12:56 PM
Because the first parameter, the variable that needs to change, will change. This is so I can display and set variables at the same time by using parallel.waitForAll(disp(), sv(var, 1))
CometWolf #4
Posted 26 May 2014 - 01:21 PM
First off, you should REALLY go read up on what parallel actually does. Second, that won't actually work since you can't pass parameters to the functions used in parallel directly. And finally, even if parallel worked the way you seem to think it does, it would be utterly pointless to use it that way. The variable updates faster than your eyes could ever dream of processing, even if it's inbetween screen refreshes.
theoriginalbit #5
Posted 26 May 2014 - 01:32 PM
no one going to mention that it won't work anyway 'cause Lua is pass-by-value, not pass-by-reference (except with tables and technically functions)?
Edited on 26 May 2014 - 11:32 AM
CometWolf #6
Posted 26 May 2014 - 01:36 PM
Well yes, what he's currently doing won't work. I can however think of a few creative approaches that could work, but that's beside the point, since it's a pointless thing to do in the first place.