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

Variables with variables in the name

Started by pcmaster160, 20 May 2012 - 08:12 PM
pcmaster160 #1
Posted 20 May 2012 - 10:12 PM
Variableception :P/>/>
But I know how in php you can just go myvar$x and if x was 10 it would be myvar10 and try to read that. So i know in lua it uses ..x.. as the escape key for variables in strings. but how would this work in variable names?

Heres what i tried but it didnt work with the unexpected smybol error.
x=1
while x<5 do
if out..x..==1 then
res=res+1
end
if out..x..==0 then
dom=dom+1
end
end
i have out1,out2,out3 and out4 as variables. and want to bulk read them.
Luanub #2
Posted 20 May 2012 - 10:38 PM
You have to many ..'s. For the escape you add ..'s before/after only if there is something before or after.

change

if out..x..==1 then

to (also this will be a string and not a number, so to check it this way add some double quotes around the number or you will have to convert out..x to a number)

if tonumber(out..x) == 1 then

Edited on 20 May 2012 - 08:43 PM
Cloudy #3
Posted 20 May 2012 - 10:46 PM
If you place the variable in the global scope you can do this:
_G["myvar"..x]
to reference it.
pcmaster160 #4
Posted 20 May 2012 - 11:43 PM
k thanks i got it working.
Lyqyd #5
Posted 21 May 2012 - 12:30 AM
This is something one should really be using tables for. This example will use the table "out", with entries out.1, out.2, out.3 and out.4, each of value 1 or 0:


for i=1,4 do
    if out[i]==1 then
        res=res+1
    elseif out[i]==0 then
        dom=dom+1
    end
end

Even better, using booleans instead of numerical values:


for k, v in pairs(out) do
    if v then
	    res = res + 1
    else
	    dom = dom + 1
    end
end

The second one will automatically evaluate all of the entries in the "out" table.