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

[lua] [solved] Function arguments

Started by darkrising, 18 October 2012 - 05:08 PM
darkrising #1
Posted 18 October 2012 - 07:08 PM
Hi again! I have a function which loads a file name which it is passed, code:


function arrayLOAD(FileName2)
  if (fs.exists(FileName2) == true) then
	dofile(FileName2)
  else
	local file = io.open(FileName2,"w")
	file:write(FileName2.." = {}")
	file:close()
	dofile(FileName2)
  end
end

I use this a lot for storing tables, my question is:

how can I go from:

arrayLOAD("table1")
arrayLOAD("table2")
arrayLOAD("table3")

to:

arrayLOAD("table1", "table2", "table3")

I know that it is not much of a difference but It would save a lot lines!
MysticT #2
Posted 18 October 2012 - 07:11 PM
You want to use variable arguments:

local function arrayLOAD(...)
  for _, filename in ipairs({ ... }) do
    -- your code here
  end
end
Noodle #3
Posted 18 October 2012 - 07:12 PM
hmm..
I could remake your function or suggest what to do with it?
Dammit Mystic.. I was doing the same, just completing the code -.-
Ditto8353 #4
Posted 18 October 2012 - 07:18 PM
You can write the function so it can take any many files as you want!


function arrayLOAD(...)   --//This means we don't know how many arguments we will get.
   local arg = {...}   --//This puts all of the arguments into a table called 'arg'
   for i=1,#arg do   --//This loops through all the arguments, starting at 1 and going to the length of the arg table '#arg'
	  if (fs.exists(arg[i]) == true) then
		 dofile(arg[i])
	  else
		 local file = io.open(arg[i],"w")
		 file:write(arg[i] .. " = {}")
		 file:close()
		 dofile(arg[i])
	  end
   end
end

Edit: Mystic's code is a much better solution to this. It may not make sense unless you know what ipairs({…}) does
Sammich Lord #5
Posted 18 October 2012 - 07:18 PM
hmm..
I could remake your function or suggest what to do with it?
Dammit Mystic.. I was doing the same, just completing the code -.-
Mystic always beats everybody to the draw. :P/>/>
Noodle #6
Posted 18 October 2012 - 07:19 PM
hmm..
I could remake your function or suggest what to do with it?
Dammit Mystic.. I was doing the same, just completing the code -.-
Mystic always beats everybody to the draw. :P/>/>
Technically I was here before him, I was just remaking the code, he just made that loop that I was doing.
darkrising #7
Posted 19 October 2012 - 12:04 AM
Ok cool, thanks for the help! you guys are the best :P/>/>