lua-users home
lua-l archive

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


( ... ) but why would the first argument to my function be
dropped in the former case and not in the latter?

Let's look to your __index again:

> jgl = {}
> jgl_meta = { __index = function(t, k)
>                         print("__index: " .. k)
>                        return function(t, ...)
>                            jgl.set_command_buffer(k, ...)
>                        end
>                     end
>                   }

The __index metamethod (function) consumes 1 argument (the (k)ey in question) and then return a closure. So far so good.

Then the returned closure will consume _another_ argument (named 't') and then call jgl.set_command_buffer with the remaining params.

Solution: just remove 't' from the (latter) arg list or always calls the method with the ':' syntax - jgl:line(2,3,4,5).

You could also check if 't' is the table itself, ignoring it:

jgl = {}
jgl_meta = {
    __index =
    function( t, k )
        print( "__index: " .. k )
        return
        function ( tt, ... )
            if tt == t then
                jgl.set_command_buffer( k, ... )
            else
                -- Include 'tt' to the output
                jgl.set_command_buffer( k, tt, ... )
            end
        end
    end
}

setmetatable( jgl, jgl_meta )

command_buffer = { }

function jgl.set_command_buffer( ... )
    print( "command: " .. table.concat( { ... }, ", " ) )
    command_buffer[ #command_buffer + 1 ] = { ... }
end

jgl.line( 2.0, 3.0, 4.0, 5.0 )
jgl:line( 2.0, 3.0, 4.0, 5.0 )

Output:

__index: line
command: line, 2, 3, 4, 5
__index: line
command: line, 2, 3, 4, 5


--rb