I'm programing with Lua recently and tired about writing some code like
if variable ~= nil then
variable.function()
end
I know in C# or Swift, we can do something like
variable?.function()
Does Lua have some ways to approach this kind of feature?
From "Programming in Lua", 4th edition, section "Tables":
Lua does not offer a safe navigation operator, and we do not think it should. Lua is minimalistic. Moreover, this operator is quite controversial, with many people arguing —not without some reason— that it promotes careless programming. However, we can emulate it in Lua with a bit of extra notation.
The bit of extra notation suggested could be for your case;
((variable or {}).func or function() end)()
This checks whether variable is nil (or false) and if not so, tries to access its entry func (note that you can't name a function function because that's a keyword) - if that doesn't exist, it returns a function doing nothing, otherwise it returns the function variable.func. The resulting function is immediately invoked.
I don't think this is very readable though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With