Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Lua has something like variable?.function() as in Swift or C#?

Tags:

lua

Hello Guys!

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?

like image 401
鍾孟儒 Avatar asked Nov 14 '25 14:11

鍾孟儒


1 Answers

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.

like image 194
lubgr Avatar answered Nov 17 '25 07:11

lubgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!