I don't think the point of global is to create a global variable, but
moreso to update one. Julia follows Python rules,
aa = 10
function foo()
aa = 20
end
foo()
aa # returns 10. Would return 20 if global had been used.
I've also seen a lot of code like
function bar()
@eval global const uu = 10
end
that replace macros in some cases. global isn't necessary here, but people
use it for clarity.
I use global in dlet to implement special variables:
""" Dynamic-let. Performs bindings that are reverted at the end of the
scope.
Sample usage:
```
g_var = nothing
g_list = [1,2,3,4]
function foo()
@dlet(g_var=Something(), # temporarily binds g_var
g_list[2]=100) do # temporarily changes g_list[2]
...
end
end
```
- @dlet(x=10) do ... will bind x in the global scope
- It works with dictionary elements, arrays, object fields, etc.
- Unfortunately, `dlet(some_list[bar()] = 5) do ...` will call bar() thrice
- As usual, globals are slow. Consider using
`const g_var = fill(initial_value)` to specify the type of g_var
"""
macro dlet(do_body, assignments...)
binds = map(macro_keyword_args, assignments)
temp_vars = map(_->gensym(), binds)
quote
$(map(esc, [:($tvar=$var)
for (tvar, (var, _)) in zipe(temp_vars, binds)])...)
try
$(map(esc,
[isa(var, Symbol) ? :(global $var = $val) : :($var = $val)
for (var, val) in binds])...)
($(esc(do_body)))()
finally
$(map(esc,
[isa(var, Symbol) ? :(global $var = $tvar) : :($var =
$tvar)
for (tvar, (var, _)) in zipe(temp_vars, binds)])...)
end
end
end
On Tuesday, April 12, 2016 at 8:05:36 AM UTC-4, Didier Verna wrote:
>
> Mauro <[email protected] <javascript:>> wrote:
>
> > If I understand correctly, you argue that all global bindings should
> > be declared in the (lexical) global scope. An inner scope could then
> > use that binding by using `global`. But new global bindings could not
> > be created in local scopes. I think that would functionally be
> > equivalent to the current status. I have no feeling about which would
> > be superior syntactically.
>
> Right. It's the implicit creation of new bindings that I dislike. Or
> rather, the fact that sometimes new bindings are created, sometimes
> not, depending on the context.
>
> >> 2. also, technically, your lexical closure isn't required for the
> >> function itself, but for the particular method you're defining. But I
> >> guess there's no way of declaring an empty generic function?
> >
> > function foo end
>
> Oh! So, it's exactly that. Your previous example:
>
> let tunnel_port = 9201
> global next_tunnel_port
> function next_tunnel_port()
> # ...
> end
> end
>
> can actually also be written like this:
>
> function next_tunnel_port end
> let tunnel_port = 9201
> function next_tunnel_port()
> # ...
> end
> end
>
>
> --
> ELS'16 registration open! http://www.european-lisp-symposium.org
>
> Lisp, Jazz, Aïkido: http://www.didierverna.info
>