200 posts
Location
Scotland
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!
1604 posts
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
864 posts
Location
Sometime.
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 -.-
136 posts
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
1214 posts
Location
The Sammich Kingdom
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/>/>
864 posts
Location
Sometime.
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.
200 posts
Location
Scotland
Posted 19 October 2012 - 12:04 AM
Ok cool, thanks for the help! you guys are the best :P/>/>