lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I think you could achieve the same behaviour easier:

function concat(s)
    return setmetatable({s},{
        __call=function(t,s) table.insert(t,s) return t end,
        __tostring=function(t) return table.concat(t," ") end
    })
end

print( concat "a" "b" "c" )

вс, 20 окт. 2019 г. в 18:16, Mattia Maldini <mattia512maldini@gmail.com>:
>
> Hello everyone,
> I started using Lua for fun and was amazed by the huge flexibility such a simple language allows.
> I am writing here to possibly push a suggestion. For function calls with a single argument Lua allows to omit the parenthesis if the argument is a string. Would it be possible to extend this notation to variables as well?
>
> I'm proposing this because I have a soft spot for functional programming notation (Haskell, Elm,...). I know Lua only allows the first (string) argument to be passed this way, but it is easy to natively implement partial functions that extend this notation to the full list:
>
>
> ```
> local function arraycat(t1, t2)
>     for i = 1, #t2 do t1[#t1 + 1] = t2[i] end
>     return t1
> end
>
> local function intermediatefun(params, nargs, fun)
>     local parameters = params
>     return function(...)
>         local arg = {...}
>         parameters = arraycat(parameters, arg)
>         if #parameters >= nargs then
>             return fun(unpack(parameters))
>         else
>             return intermediatefun(parameters, nargs, fun)
>         end
>     end
> end
>
> -- makes a function that accepts partial arguments (i.e. passing a first argument returns
> -- another function with the fixed first argument)
> function letfun(nargs, fun)
>     return function(...)
>         local arg = {...}
>         if #arg >= nargs then
>             return fun(unpack(arg))
>         else
>             return intermediatefun(arg, nargs, fun)
>         end
>
>     end
> end
>
> concat = letfun(3, function(x, y, z)
>     return x .. y .. z
> end)
>
> print(concat "hello" " Lua" " world")
> ```
>
> With this code I can almost achieve what I'm looking for, and I can invoke a function with a space-separated list of strings. I really wish I could do the same with regular variables.