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

starting one function from a program

Started by bash76, 30 December 2012 - 01:55 AM
bash76 #1
Posted 30 December 2012 - 02:55 AM
Hi forum,

I am new to LUA and CC but got some programing experience, but i don't know how to start a specific function from a program without running the rest.

Example program doStuffA2C:
Spoiler

tArgs = {...}
sArgs1 = tArgs[1]
sArgs2 = tArgs[2]

function.a()
do a
end

function.b()
do b
end

function.c()
do c
end

if tArgs == nil then
  a()
  b()
  c()
else
  for i=1,2 do
  // this won't work but i write this so you may see how i want it to work
  sFunction = sArgs..i.."()"
  // so now i want the argument to be the name of the function to call and
  // this part to actually turn it into the calling parameter - thus if sArgs1 = b
  // call function b - see below

First i wonder if its possible to call the programm like this
doStuffA2C b
to just call function b.

The second question is, if it is possible to create a string from an argument and let this string be the function to call in this programm.

I know, i cloud work around this, creating 3 programs, and call them one by one, thus not to have to call the functions. But i just wonder how to make this within one program. Why? More difficult :D/>

Thx
GopherAtl #2
Posted 30 December 2012 - 03:45 AM
getfenv can let you accomplish this. it returns a table containing all the functions and variables in the current code context, keyed by their names.


local tArgs={...}

function a()
  print("doing a")
end

function b()
  print("doing b")
end

function c()
  print("doing c")
end

--if there's 0 args...
if #tArgs==0 then
  --do all of it, or whatever
  a()
  b()
  c()
else --more than 0 args
  --grab my function environment as a table
  local tEnv=getfenv()

  --for each arg index...
  for i=1,#tArgs do
	--check if it exists in the function environment, and is a function
	if tEnv[tArgs[i]]==nil or type(tEnv[tArgs[i]])~="function" then
	  error("no such function '"..tArgs[i].."'")
	end
	--call it
	tEnv[tArgs[i]]()
  end
end
bash76 #3
Posted 30 December 2012 - 09:19 AM
Awesome! Thx!
ChunLing #4
Posted 30 December 2012 - 08:21 PM
Or…you could just put them in the table yourself. That will also save you on typing out local a bunch, in case you didn't want those functions to be global (which, if you're going to be calling this from inside other programs, which I suspect you might for some reason, would be a thing). And it'll save your computer a bit of work.