2

Consider this code:

OperatorTable addOperator(":", 2)

: := method(value,
  list(self, value)
)

hash := "key": "value"
hash println

The return should be list(key, value), and when using this in the Io REPL that is exactly the return value. When using the interpreter (as in io somefile.io) the value returned is value. After some inspection the difference is here:

# In the REPL
OperatorTable addOperator(":", 2)
message("k" : "v") # => "k" :("v")

# Via the Interpreter
OperatorTable addOperator(":", 2)
message("k" : "v") # => "k" : "v"

Why is this happening?

Nathan Kleyn
  • 5,103
  • 3
  • 32
  • 49
krainboltgreene
  • 1,841
  • 2
  • 17
  • 25

2 Answers2

4

File execution happens in these stages:

  • load file
  • replace operators based on the current operator table
  • execute contents

So operator to message conversion only happens when the file is initially loaded in stage 2. When the operator registration code is executed in stage 3. this has already happened, thus the operator has no effect.

You can set the order which files get loaded manually and put the operator definition in the first file loaded. Having a file called operators.io for example which includes all operator definitions loaded before the files that use them.

j-pb
  • 822
  • 2
  • 8
  • 12
  • It's at the top of the only file loaded, and yet still has no effect. – krainboltgreene Apr 30 '12 at 11:59
  • 3
    Doesn't matter. As ticking points out, it's done at compile time, not execution time. Io has a compile time ahead of any execution (even the first expression in your file), this is when operator shuffling occurs. Therefore, by the time the system executes your first expression in the file, it's already too late to make changes to the operator table that affect that file. Think of it like trying to change your car tire after you've started driving without first pulling over and stopping. – jer May 01 '12 at 04:23
2

After confirming with ticking I arrived at the following solution:

main.io:

doFile("ops.io")
doFile("script.io")

ops.io:

OperatorTable addOperator(":", 2)
: := method(value,
            list(self, value))

script.io:

hash := "key": "value"
hash println

Like ticking explains, the whole file is loaded at once so you have to split it up so the loading order guarantees that the operators are available.

locks
  • 6,537
  • 32
  • 39