开发者

Modifying a variable in enclosing scope

开发者 https://www.devze.com 2023-03-31 08:36 出处:网络
There is a common problem in languages that assume variable declarations are local. How do you get at variables in enclosing scopes.

There is a common problem in languages that assume variable declarations are local. How do you get at variables in enclosing scopes.

Is there a way in Opa?

For example:

start() = 
    name = Random.string(5)

    set_name(new_name) = 
        old_name = name
        name = new_name
        log("User {old_name} changed name to {new_name}")

This doesn't work. We get a warning that name is unused in set_name, and the value of name in start is never changed.

In a language like Lua, Javascript or Scheme, there is explicit marking of locals, so variables not marked in that way can be found in the scope stack. In Python there is no such marking, and so this would be impossible. In Python you can get at global (toplevel) variables, and I've found the @toplevel directive in Opa too. But I'm interested in intermediate points in the scope chain.

There are work开发者_如何学Carounds, of course, by using records, but is there a direct route?


One solution is to use Reference module :

Reference.create, Reference.get, Reference.set

http://opalang.org/resources/doc/index.html#stdlib.core.reference.opa.html/!/value_stdlib.core.Reference


Reference module mentioned in Fred's answer is indeed one solution to this and it's closest to what you are asking for.

But it's also good to know that when programming the "right way" most of the state in your Opa program will be captured in Sessions, with a change to the session's state triggered by a message send to it.

0

精彩评论

暂无评论...
验证码 换一张
取 消