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

Use an array for function arguments?

Started by OhTrueful, 06 August 2014 - 02:55 AM
OhTrueful #1
Posted 06 August 2014 - 04:55 AM
Simple question, but I see no simple answer…

I have a 1D table of arguments I want to use for a function, however I don't know how many args there are. So how would I call the function with a variable number of args?

Heres an example:


function fn(...)
  for i = 1, #arg do
	print(arg[i])
  end
end
x = {"I", "want", "to", "print", "all", "these", "things"}
fn(x)  --  This obviously won't work...

Please Note: Clearly this is a terrible way to approach the code I put in the example, but that code is a major simplification of my real use for this.
Edited on 06 August 2014 - 02:58 AM
KingofGamesYami #2
Posted 06 August 2014 - 05:07 AM
Well, you can do this

function fn( ... )
  local tArgs = { ... }
  for i = 1, #tArgs do
   print( tArgs[ i ] )
  end
 end
end
fn( "I", "want", "to", "print", "all", "these", "things" )
--#optionally
local x = { "I", "want", "to", "print", "all", "these", "things" }
fn( unpack( x ) )
--#or of course
function fn( tArgs )
 for i = 1, #tArgs do
  print( tArgs[ i ] )
 end
end
local x = { "I", "want", "to", "print", "all", "these", "things" }
fn( x )
theoriginalbit #3
Posted 06 August 2014 - 05:11 AM
As detailed in the PIL, use unpack to give any sequentially indexed values in the tables to your vararg function.


local function func(...)
  for _,value in pairs( {...} ) do
    print( value )
  end
end

local x = {"I", "want", "to", "print", "all", "these", "things"}
func( unpack(x) )

as you may notice I have used {…} over arg, this is because the auto-generated table arg contains a value which is the number of values in the table.
OhTrueful #4
Posted 06 August 2014 - 05:29 AM
Thank you both!

All I needed is the unpack() function. Because I am using this to call any function, not just one, I don't want to change anything in the function (fn) itself.
So I can just do (in this example):

fn(unpack(x))
Edited on 06 August 2014 - 03:31 AM