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

Trouble choosing from multiple variables to run in peripheral?

Started by Kraethi, 10 August 2014 - 04:22 PM
Kraethi #1
Posted 10 August 2014 - 06:22 PM
Sorry about the vagueness of the title.

I have a program that uses a command block and a system of menus to apply effects to players.

Here is the Menu code for selection:

Spoiler

os.pullEvent = os.pullEventRaw
term.clear()
term.setCursorPos(1,1)
local commandBlock = peripheral.wrap("bottom")
local function menu(...)
local sel = 1
local list = {...}
local offX,offY = term.getCursorPos()
local curX,curY = term.getCursorPos()
while true do
  if sel > #list then sel = 1 end
  if sel < 1 then sel = #list end
  for i = 1,#list do
   term.setCursorPos(offX,offY+i-1)
   if sel == i then
	cPrint("["..list[i].."]")
   else
	cPrint(" "..list[i].." ")
   end
end
while true do
local e,e1,e2,e3,e4,e5 = os.pullEvent()
if e == "key" then
  if e1 == 200 then
   sel = sel-1
   break
  end
  if e1 == 208 then
   sel = sel+1
   break
  end
  if e1 == 28 then
   term.setCursorPos(curX,curY)
   return list[sel],sel
  end
end
end
end
end

That's some modified code I got from somewhere around here that has a nice little graphic selection by putting brackets around items. It returns the name of the item selected when the user hits enter. cPrint is a little function to print centered text.

My problem is that I'm trying to input effect IDs to a command block. I can't select "Strength" and input that in the command block because it won't recognize it. It needs the number, so I'm trying to transform the menu selection into the number and save that as the id variable. My idea for that, though, isn't working.

Here's a snippet:

elseif list1 == "Damage" then
local id = "7"
local amplifier = "1"
elseif list1 == "Nausea" then
local id = "9"
local amplifier = "1"

And the function for the effect:

function affect(...)
commandBlock.setCommand("effect "..target.." "..id.." "..duration.." "..amplifier.."")
commandBlock.runCommand()
end

affect(target,id,duration,amplifier)

I had the program print all of the variables before running and the only thing it delivered was the username, which is read by target = read().

How can I transform the menu outputs into the local variables??

Attached is the program file in totality.

Thanks, guys.
natedogith1 #2
Posted 11 August 2014 - 05:51 AM
Your variables are out of scope. Since you're defining 'id' and 'amplifier' as local inside of an if statement, nothing outside of that if statement can read it. instead of
if test then
  local a=123
end
you should do
local a
if test then
  a=123
end
I hope that made sense.
Kraethi #3
Posted 11 August 2014 - 06:32 AM
Thank you so much! That helps a lot.

Edit: and after my initial burst of enthusiasm, it worked! Thanks so much.
Edited on 11 August 2014 - 04:38 AM