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

Function with variables

Started by tysciman7, 07 June 2013 - 11:09 PM
tysciman7 #1
Posted 08 June 2013 - 01:09 AM
im trying to make it easy for myself for just a brief amount of time so i want to type the program then be able to say with fucntion i want to run at the time


local x = read()
x()

thats basically what i want to do but of course it doesnt work like that
theoriginalbit #2
Posted 08 June 2013 - 01:17 AM
This was answered not that long ago, have a read of the thread: http://www.computercraft.info/forums2/index.php?/topic/13077-call-function-from-string/page__pid__121380#entry121380
tysciman7 #3
Posted 08 June 2013 - 01:19 AM
How does that help me?
remiX #4
Posted 08 June 2013 - 05:45 AM
local x = read()
local f = loadstring(x)
local ok, err = pcall(f)
if not ok then
-- error with typed code
end

I think that's right.. :P/>
theoriginalbit #5
Posted 08 June 2013 - 06:14 AM
How does that help me?
Well if you have a bunch of functions in the file and want to run a specific one based off input you use that code.

And if you're wanting a program where you type the function into read and then when you press enter it runs that function then the first answer would have pointed you in the right direction (i.e. what remiX just posted)
Things #6
Posted 09 June 2013 - 03:12 AM
So you want to be able to call a specific function inside a program? In which case you could use a table with {…} to get the parameters, then use an if statement to check if it's a valid function.

For example:



args = {...}
  for i=1,#args do
   if args[i] == "functionname" then
     runfunction()
  end
  if args[i] == "functionname2" then
    runfunction2()
  end
end

That's how I read it anyway :)/>
ElvishJerricco #7
Posted 09 June 2013 - 04:11 AM
How does that help me?

Since you apparently didn't read much of that thread posted above, I'll help you out. The best, most reliable way of doing it is to store your functions in a table. You could do some getfenv() stuff but in rare, odd scenarios that could go wrong.


local myFuncs = {}

function myFuncs.foo()
	print("bar")
end

local x = "foo"
myFuncs[x]()

This prints "bar"! You're storing your functions by name in a table, then referencing that name with a string variable. That's what you're looking for, no?