feat: Add Support for Accessing Index Values Using the Dot Operator
Enhanced the codebase to enable index value access through the dot operator.
Code
package main
import (
"fmt"
"strings"
"github.com/skx/monkey/evaluator"
"github.com/skx/monkey/lexer"
"github.com/skx/monkey/object"
"github.com/skx/monkey/parser"
)
func main() {
condition := `
let a = [{"name":"monkey",
true:1, false: {"test": "multiTest"},
7:"seven"}];
puts(a[0].false["test"], "\n")
puts(a.0.false.test, "\n")
puts(a[0].true, "\n")
puts(a.0[true], "\n")
`
env := object.NewEnvironment()
p := parser.New(lexer.New(condition))
expr := p.ParseProgram()
if len(p.Errors()) != 0 {
fmt.Printf("failed to parse conditional program: %s", strings.Join(p.Errors(), "; "))
} else {
res := evaluator.Eval(expr, env)
fmt.Println(res)
}
}
Output
multiTest
multiTest
1
1
&{}
@skx : Could you please review this PR?
Thanks in Advance
Ganesan
If this only covered hash-keys I'd say "that's great, thanks".
But looking at a.0.xxx instead of a[0].xxx really loses the fact you're looking at an array, and I don't really like that. I guess there's a bit of an open question on this repository, how active it is:
- I read the book and hacked around.
- Then I looked at other projects, and forked one.
- I added some features.
- I added some more.
- Then I kinda left it alone, because I thought I was done.
- I leave it here because I know the repository comes up in searches, and other people have completed the book and look for inspiration.
- I've seen people literally copy my pull requests 100% to add new features to their interpreter, and that's absolutely OK.
But new features? I feel like I've done enough - I did consider adding support for structs/classes, but decided that it would be a bit annoying and ignored the idea.
I'm happy to see bug reports from people, and you've submitted several which have been really useful and well-spotted. But I think new features are perhaps better off made against your own fork - we probably have different ideas on what is useful, and what is sane.
So in my case I'd say hash-indexes? Yes. Array-indexes? No.
If you reworked it to only do that I'd merge, but honestly if you're planning more syntax changes and additions you might as well just take your own copy/fork and run with it. I don't want to stop anybody experimenting or learning, but given that I don't use this repository adding random things to it - short of clear error-fixes - is perhaps not so useful.