Page 1 of 1
multiple function arguments
Posted: Tue Nov 21, 2017 10:50 am
by PGUp
so i wanna make a function to generate polygon with color, it looks like this
Code: Select all
function poly(... , color)
local edges = {...}
local color = color
end
even when i dont run the function, i got an error already, how can i achieve this ?
Re: multiple function arguments
Posted: Tue Nov 21, 2017 11:09 am
by bartbes
The problem is that you can only have varargs as the last argument(s). So if you rewrite your function like this, it won't error:
Code: Select all
function poly(color, ...)
local edges = {...}
end
(Note that color is already a local, as it is an argument, so 'local color = color' doesn't actually do anything useful.)
Re: multiple function arguments
Posted: Tue Nov 21, 2017 11:20 am
by PGUp
bartbes wrote: ↑Tue Nov 21, 2017 11:09 am
The problem is that you can only have varargs as the last argument(s). So if you rewrite your function like this, it won't error:
Code: Select all
function poly(color, ...)
local edges = {...}
end
(Note that color is already a local, as it is an argument, so 'local color = color' doesn't actually do anything useful.)
alright, but how do i check if the color is not nil ? using color ~= nil return an error
Re: multiple function arguments
Posted: Tue Nov 21, 2017 11:33 am
by Sir_Silver
So you're saying you should be able to pass edges to the function while not passing a color, correct?
Is the "color" that you're passing a table that looks something like this? {255, 0, 0}. If that's what a "color" is then you could try this...
Code: Select all
function poly(color, ...)
local args = {...}
local edges = {}
if type(color) ~= "table" then
edges[1] = color
end
for i = 1, #args do
table.insert(edges, args[i])
end
end
Re: multiple function arguments
Posted: Tue Nov 21, 2017 11:44 am
by zorg
I'd also be interested in where you got a error with color ~= nil, since that should work under most circumstances.
Code: Select all
local color = color or {255,255,255,255}
----
local color = color ~= nil and color or {255,255,255,255}
----
local color = type(color) ~= 'nil' and color or {255,255,255,255}
----
-- And the same 3 ways can be used with if-then-else, as well.