Jump to content




Function with variables


  • You cannot reply to this topic
6 replies to this topic

#1 tysciman7

  • Members
  • 41 posts

Posted 08 June 2013 - 12: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

#2 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 08 June 2013 - 12:17 AM

This was answered not that long ago, have a read of the thread: http://www.computerc...380#entry121380

#3 tysciman7

  • Members
  • 41 posts

Posted 08 June 2013 - 12:19 AM

How does that help me?

#4 remiX

  • Members
  • 2,076 posts
  • LocationSouth Africa

Posted 08 June 2013 - 04: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

#5 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 08 June 2013 - 05:14 AM

View Posttysciman7, on 08 June 2013 - 12:19 AM, said:

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)

#6 Things

  • Members
  • 15 posts
  • LocationAustralia

Posted 09 June 2013 - 02: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 :)

#7 ElvishJerricco

  • Members
  • 803 posts

Posted 09 June 2013 - 03:11 AM

View Posttysciman7, on 08 June 2013 - 12:19 AM, said:

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?





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users