1

I have a set of variables that holds quantity info and x to select the one I use. How can I concatenate the letter s and var x and have it read as s2 or s3 etc. The code I managed to find does not work.

x = 2 
s1 = false
s2 = 64
s3 = 64
s4 = 64
s5 = 0

if s2 >= 0 then
x = 2
elseif s3 >= 0 then
x = 3
elseif s4 >= 0 then
x = 4
elseif s5 >= 0 then
x = 5
end

if turtle.placeDown() then
 tryUp()
 turtle.select(1)
 _G["s"..x] = _G["s"..x] - 1 
end
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • 3
    `_G["s"..x]` looks correct. How do you know it doesn't work? – Yu Hao Jul 09 '14 at 03:33
  • 1
    The code [works](https://eval.in/170740). Though in general doing this with a local table of your own is better than using _G but . – Etan Reisner Jul 09 '14 at 03:54
  • Your `if-elseif-end` branchy structure could also be transformed using the same trick: `for i=2,5 do if _G['s'..i]>=0 then x=i break end end` – Egor Skriptunoff Jul 09 '14 at 12:11
  • the error i get is: attempt to preform arithmetic __sub on nil and number I am doing this in computercraft (if you didn't already know) the version of Lua is Luaj-jse 2.0.3 – user3818682 Jul 10 '14 at 01:59
  • The reason the code looks correct is that there are no declarations for s1, s2, s3, s4, s5. So, we assume they are global. But, if there is unseen code that declares as local then using _G won't work. – Tom Blodget Jul 10 '14 at 16:46
  • Thank you Tom! To correct code add _G.s2 = s2 _G.s3 = s3 _G.s4 = s4 _G.s5 = s5 – user3818682 Jul 10 '14 at 22:54

1 Answers1

0

Why would you need to do that?

My suggestion to improve your code would be something like this:

local s = {false, 64, 64, 64, 0}

for i = 2, #s do
  if s[i] >= 0 then
    x = s[i]
  end
end

if turtle.placeDown() then
  tryUp()
  turtle.select(1)
  x = x-1
end

Using a loop makes the code somewhat neater, and there is no real need for you to use global variables. If you insist on using _G with the string concatenation with your original code, try this:

x = 2 
s1 = false
s2 = 64
s3 = 64
s4 = 64
s5 = 0

if s2 >= 0 then
x = "2" --Notice the string here
elseif s3 >= 0 then
x = "3"
elseif s4 >= 0 then
x = "4"
elseif s5 >= 0 then
x = "5"
end

if turtle.placeDown() then
 tryUp()
 turtle.select(1)
 _G["s"..x] = _G["s"..x] - 1 
end

This replaces all the x values with strings instead of numbers, which was probably what was causing the error

Lee Yi
  • 517
  • 6
  • 17