[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua style guide ?
- From: Hisham <h@...>
- Date: Wed, 7 Jun 2017 20:50:58 -0300
On 7 June 2017 at 09:41, Peter Aronoff <telemachus@arpinum.org> wrote:
> Russell Haley <russ.haley@gmail.com> wrote:
>> I found your code in Moses very readable and well structured but
>> I noticed you use '_' for some 'root' level variables (for lack of
>> a better term). My understanding (I think I read it somewhere) was '_'
>> was supposed to be used in cases where you weren't going to use the value
>> like in:
>
> Re "I think I read it somewhere". The use of _ for unused/throwaway
> variables is definitely a convention in Lua. Maybe you read this in
> Roberto's Programming in Lua? "Usually, I reserved the identifier _ (a
> single underscore) for dummy variables" (page 5 in the 3rd edition). But
> you may have read it in the wiki's style guide or a bunch of other places.
>
> If I had to guess, the original tendency may have started with PiL, but
> maybe people who have been in the community longer would know better.
This practice comes from other languages. In Haskell function
declarations, for example, _ means a "don't care" pattern:
printFirstInList [] = "list is empty"
printFirstInList (x : _) = "first element is " ++ show x
Here, the rest of the list is being "discarded" with a _. Haskell
actually enforces it so that you can't "use" _ (it's only a pattern
and not actually a variable). In Lua, however, that is a variable, so
that is more of a notation convention:
for name, _ in pairs(entries) do
print("name: " .. name)
end
In this traversal, only keys are being used and not values. _ being a
regular variable means that nothing would stop us from doing print(_),
but it's a convention that when we declare _ we mean we won't ever use
its value.
Likewise, I sometimes also do this:
local _, val = function_for_which_i_only_need_the_second_result()
-- Hisham