I read all the docs I could find on the Lua language, but the use of local keyword when creating default values for function parameters is still unclear to my mind.
I see this a lot. I imagine the local keyword should be used in this instance.
function my_func(someArg)
local someArg = someaArg or 'someDefaultValue'
end
What about the case where the default value can also be false. This is how I code it at the moment, but I'm not sure if it's the best. I'm not using the local keyword as I am assuming it is not needed with function parameters.
function my_func(someArg)
local someArg = someaArg or 'someDefaultValue'
end
I think you mean someArg instead of someaArg
Am I right that the first version should use local, but not the second?
You don't need to declare the local in the first example.
In fact some languages (like Python I think) prohibit redeclaring an existing identifier (in local scopes).
It looks confusing and may lead to bugs.
What about the case where the default value can also be false
All arguments passed to a function are automatically local. I think the manual says that, but it's good to know.
Earliest Love2D supporter who can't Love anymore. Let me disable pixel shaders if I don't use them, dammit! Lenovo Thinkpad X60 Tablet, built like a tank. But not fancy enough for Love2D 0.10.0+.
local someDefaultValue = 20
function my_func(someArg)
someArg = someArg or someDefaultValue
print(someArg)
end
my_func() -- 20
my_func('something') -- something
my_func(false) -- 20
If you actually want someArg to be able to contain a boolean value, then you want to explicitly check for nil. It just depends on whether you care about boolean values or not inside my_func.
1) I'm a little surprised that local is not needed in my first example since all the code Iv'e looked at for Love always seems to use it. I'm thinking of Hump as an example.
2) I should have been more specific. My parameter can be boolean value or a string and the default is not false but a string so I must implicitly check for nil.
I read all the docs I could find on the Lua language, but the use of local keyword when creating default values for function parameters is still unclear to my mind.
I see this a lot. I imagine the local keyword should be used in this instance.
function my_func(someArg)
local someArg = someaArg or 'someDefaultValue'
end
What about the case where the default value can also be false. This is how I code it at the moment, but I'm not sure if it's the best. I'm not using the local keyword as I am assuming it is not needed with function parameters.