Creating functions with optional params

I have a basic question dealing with the Corona SDK and lua. I noticed that certain functions like display.newImage([parentGroup,] filename [,baseDirectory] [,left,top] [,isFullResolution]), have those barracks around certain params and if you do not put anything in there then it goes on with the function. I have a function Test(a,b,c) and the only way I handle it is if they put nil in any of them then skip over it but it still seems unnecessary. I was wondering if I could do the same and if I can how. [import]uid: 143008 topic_id: 26719 reply_id: 326719[/import]

You sure can. Example:

[code]
local function test(params)
local self = {}
self.a = params.a or 0 – you can also use nil or a string for instance
self.b = params.b or 0
self.c = params.c or 0

return self
end
[/code] [import]uid: 84637 topic_id: 26719 reply_id: 108343[/import]

how could i then modify those params?

test.a, test.b, test.c?? [import]uid: 105206 topic_id: 26719 reply_id: 108485[/import]

Once you have created it?

Like so:

[code]
local function test(params)
local self = {}
self.a = params.a or 0 – you can also use nil or a string for instance
self.b = params.b or 0
self.c = params.c or 0

return self
end
local assign = test( { a = 100, b = 100, c = 100 } )

–Modify it
assign.a = 200

print(assign.a) – Will now print 200

[/code] [import]uid: 84637 topic_id: 26719 reply_id: 108634[/import]

Cool, thanks!! Very useful! [import]uid: 105206 topic_id: 26719 reply_id: 108651[/import]

Just another question. When should i be using “self”?

I know for example that when you OOP (i have very very very basic conceptual knowledge about it), you use self as a first param in a class, and then, every param that is “owned” by methods, are declared by self.

But i don’t understand it’s use here. [import]uid: 105206 topic_id: 26719 reply_id: 109205[/import]

In my example you can name that table whatever you want. self just makes it more apparent.

The real use for self would be like this for instance:

local ball = display.newRect(10, 10, 20, 20)  
  
function ball:destroy()  
 display.remove(self)  
 self = nil  
end  

In that example self is passed automatically via the declaration, self is ball.

[import]uid: 84637 topic_id: 26719 reply_id: 109227[/import]

In my example you can name that table whatever you want. self just makes it more apparent.

The real use for self would be like this for instance:

local ball = display.newRect(10, 10, 20, 20)  
  
function ball:destroy()  
 display.remove(self)  
 self = nil  
end  

In that example self is passed automatically via the declaration, self is ball.

[import]uid: 84637 topic_id: 26719 reply_id: 109228[/import]