Fredrik Nylén
Fredrik Nylén

Reputation: 577

Function overloading in Lua?

I am throwing together som scripts ("scenes") in the Fibaro home automation system and need to introduce myself to how to do nice things in Lua. Fibaro has it's own debug function, but for simple testing of Lua functions not having to work all the time in the Fibaro Lua scene interface would be preferable.

There is a function fibaro:debugwhich handles simple printing of information in the interface. Basically what print does on the console. So, what I would like to do in my function is assign an alias to the one of these two functions that is available at the moment.

I tried handling it like a default value:

local printFunc = fibaro:debug or print;

which does not work. An explicit IF/ELSE block also fails:

if(fibaro:debug == nil) then printFun = fibaro:debug;else  printFun =print;end;

How do I do this?

Upvotes: 3

Views: 8296

Answers (3)

warspyking
warspyking

Reputation: 3113

local printFunc = (fibaro or {}).debug and function(...) return fibaro:debug(...) end or print

Upvotes: 0

lhf
lhf

Reputation: 72312

The colon operator can only be used in method calls and so this is a syntax error:

local printFunc = fibaro:debug or print

This can be written using the dot operator

local printFunc = fibaro.debug or print

but if fibaro.debug exists, then you'll need to supply printFunc explicitly with a fibaro object that fibaro.debug expects as its first (hidden) argument.

Upvotes: 3

Egor   Skriptunoff
Egor Skriptunoff

Reputation: 974

local printFunc = print
if (fibaro or {}).debug then 
   function printFunc(...) 
      return fibaro:debug(...)
   end
end

Upvotes: 2

Related Questions