Lua Closures on DSL Injection

Lua has a really nice no-round call syntax which, combined with function closures, allows me to write the following

local tag = 1
function test(obj)
    return 
        function(str)
            return 
            function (tbl)
                tbl.objtag = tag
                tbl.objname = str
                return tbl
            end
        end

end
test (tag) "def"
{
}

test tag "def" --error
{
}

      

However, if I remove the parentheses around (tag), it results in a compilation error. So why does Lua allow parameters without parentheses (ie "Def") and not parameters "not in parentheses" var (table in this case)?

+2


source to share


1 answer


From Programming in Lua :

If the function has one single argument, and this argument is either a literal string or a table constructor, then the parentheses are optional:



My understanding of your situation is that a tag is a local variable (which is neither a literal string nor a table constructor), so it test(tag)

always requires parentheses. You don't need parentheses around "def"

because it test(tag)

returns a function that takes a single string and that function is immediately applied to "def"

.

+3


source







All Articles