Search code examples
lua

calling a function with a table constructor?


i was learning on how to create and use a class on a youtube video and i came across this code

cc = {calo = 0, goal = 1500}
function cc:new(t)
t = t or {}
setmetatable(t,self)
self.__index = self
return t
end
a = cc:new{goal = 100}

i dont understand this part a = cc:new{goal = 100} this is the first time where i see a function being called with anything other then (). i have 2 guesses on what this does maybe it replaces the parameter of cc:new function with {goal = 100} or maybe the function is called and t table is assigned to the variable then assigning the table with {goal = 100}? pls correct me if im wrong


Solution

  • first, {goal = 100} is just an argument.

    second, cc:new{goal = 100} is equal to cc:new({goal = 100})

    this is a syntactic sugar, you can call a function without brackets if theres only one argument and its type is string or table literal

    example:

    function foo(x)
        print(x)
        return foo
    end
    
    foo "Hello" "World"
    

    this will output "Hello" and "World"

    if you want to call a function without brackets and using multiple arguments, the function you gonna call must return another function for the next argument.

    the another function is not always the original one

    it may be recursive