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

[Lua][Question]Calling Functions Dynamically With Table Values

Started by Smiley43210, 19 April 2013 - 06:38 AM
Smiley43210 #1
Posted 19 April 2013 - 08:38 AM
Hey guys,

Is there any way to call a function using a table for arguments? The number of arguments can change depending on user input. For example, if a table is set up as { "edit", "myFile" }, I want to call shell.run() with the table values as the arguments. Another example: the table is { "myFile", "arg1", "arg2", "arg3" }. I would need to call shell.run("myFile", "arg1", "arg2", "arg3"). Since the number of arguments needed can change, hardcoding
local var1 = myTable[1]
local var2 = myTable[2]
and so on wouldn't be efficient. How can I do this?
Lyqyd #2
Posted 19 April 2013 - 08:53 AM
unpack(). `shell.run(unpack(myTable))`

Also, the shell no longer requires individual arguments–it will take the whole command string in the first argument just fine. You could therefor use table.concat too, if you wanted.
Smiley43210 #3
Posted 19 April 2013 - 11:23 AM
Ah, thanks! Also, good to know about shell.run; it's much simpler.

Edit: I also just remembered loadstring(), but the above works just fine.