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

Ask User for Variable

Started by LuckyLuke, 23 July 2015 - 10:00 AM
LuckyLuke #1
Posted 23 July 2015 - 12:00 PM
Hi,

im using this code to ask a user for a global variable, this works fine in another code that i saw on the internet, but it seems that i dont get it. Unfortunalty i cannot provide you with an error, cause at the place where i am at this moment, i cannot run Java :/


testvar = AskForVar("Write something")
function AskForVar(help)
UserInterface()
print("Die Variable \""..varname.."\" wird erstellt.")
write("Bitte geben Sie den Startwert ein (Hilfe: "..help.."):")
return varname = read()
end
print(testvar)

Edit: damn, tab's havent been copied to
 tag
Edited on 23 July 2015 - 10:12 AM
wieselkatze #2
Posted 23 July 2015 - 12:24 PM
You just want to return read() - also you need to put testvar = AskForVar() below your function as AskForVar is not declared yet at the position it currently is at. It might still be loaded as you set it to be global, but still it'll use the instance created on the pervious run.

The code should then look like this:

local function AskForVar ( help )
    UserInterface() -- Unless this is just a snippet and the function has been declared before, this will error out
    print( "Die Variable \"" .. varname .. "\" wird erstellt." )
    write( "Bitte geben Sie den Startwert ein (Hilfe: " .. help .. "):" )
    return read() -- just return what read() returns
end

local testvar = AskForVar( "Write something" )
print( testvar )

I've localised your variables aswell - it just is better practice as your variables will not show up in the global scoope. Also note that local variables are faster then globals.
Bomb Bloke #3
Posted 23 July 2015 - 01:05 PM
Edit: damn, tab's havent been copied to
 tag

Disable the rich text editor. Little light switch up the top left of the posting box.
LuckyLuke #4
Posted 23 July 2015 - 01:20 PM
Oh, thank you for your advise!

UserInterface() is a very simple function that clears and sets CursorPos (will be expaned later on), its defined above the function.

Why did you put "local" to the function?
MKlegoman357 #5
Posted 23 July 2015 - 01:23 PM
Why did you put "local" to the function?

That's something you should always do: localizing all your variables. They are faster and you will not run into problems as much as with global variables.
LuckyLuke #6
Posted 23 July 2015 - 04:03 PM
Ah, didnt know, i localized only in functions or loops :)/>
Thanks for the link.