You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Feb 19, 2018. It is now read-only.
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 scopedo->value='not local :('# so we add a using keyword!# `using null` shadows all variables in the parent scopeusingnullvalue='I am local!'# however, we might need to access variables from the parent scope,# so we specify themfoo=3using foo, bar
# we can just use `foo` without worrying about overwriting anything elsevalue= foo +7
Compiles to:
varvalue,foo,bar;value='some global variable';(function(){value='not local :(';})();(function(){varvalue;value='I am local!';})();foo=3bar=7(function(){varvalue;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=3bar=7# `num` is a function argument# `foo` and `bar` are the used variables outside of scopeadd= (numusingfoo, bar) ->value= num + foo + bar
value
console.logadd5#=> 15