[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to write function x:y():f() ... end ?
- From: Dirk Laurie <dirk.laurie@...>
- Date: Tue, 26 Feb 2013 17:17:53 +0200
2013/2/26 Carsten Fuchs <carsten.fuchs@cafu.de>:
> Hi all,
>
> using Lua 5.1, I'm trying to define a method in a table that has been
> returned by a previous method call, like this:
>
> function x:y("someObject"):f()
> -- ...
> end
>
> Unfortunately, this doesn't work: <name> or '...' expected near
> '"someObject"'
>
> Alternatives that work are
>
> x:y("someObject").f = function(self)
> -- ...
> end
>
> or maybe
>
> local someObject = x:y("someObject")
>
> function someObject:f()
> -- ...
> end
>
> but these are also the only working variants that I have found, and was
> wondering if there is a way to write this closer to the former one-line
> variant?
Personally I hate implied "self" with a passion, and would
be thankful that Lua forces me not to use that one-liner.
I would leap at the opportunity to use a more descriptive
parameter name, e.g.
player:drawCard("spell").action = function(card)
-- ...
end
Of course, if that table is to have more than one method
defined for it, the second alternative is better, though
I prefer this:
local card = player:drawCard("spell")
card.action = function(card)
-- ...
end
In fact, what I really like most is:
local function act_on_spell(card)
-- ...
end
player:drawCard("spell").action = act_on_spell
I can put that function anywhere the necessary upvalues
are visible, and then I do have a one-liner, a very
readable, understandable one-liner, later.