CS2 Discussion: Features: Introduce keyword “using” for controlled scoping #57
Description
MoonScript has a using
keyword, which allows you to create a new scope only pulling in the variables from the parent scope that you need, along with being able to pass in nil to create an entirely new scope.
local
in Lua works the same way as let
does in JavaScript, so there's no Lua-specific magic going on here. using
is a compile-time feature which checks for the variables used outside of the using
block against the ones provided, or lack thereof, and declares them locally accordingly.
Here's how it'd work in JavaScript, assuming we don't limit the keyword to just function definitions.
value = 'some global variable'
# the way things are now, no way to create a variable called `value` within a new scope
do ->
value = 'not local :('
# so we add a using keyword!
# `using null` shadows all variables in the parent scope
using null
value = 'I am local!'
# however, we might need to access variables from the parent scope,
# so we specify them
foo = 3
using foo, bar
# we can just use `foo` without worrying about overwriting anything else
value = foo + 7
Compiles to:
var value, foo, bar;
value = 'some global variable';
(function() {
value = 'not local :(';
})();
(function() {
var value;
value = 'I am local!';
})();
foo = 3
bar = 7
(function() {
var value;
value = foo + bar;
})();
However, because there might be some random using
function out there in the wild, a viable alternative is limiting the feature to functions, like MoonScript does.
value = 'Some global variable'
foo = 3
bar = 7
# `num` is a function argument
# `foo` and `bar` are the used variables outside of scope
add = (num using foo, bar) ->
value = num + foo + bar
value
console.log add 5 #=> 15