Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Value for a missing key in a map #272

Closed
c4s4 opened this issue Jul 26, 2018 · 6 comments
Closed

Value for a missing key in a map #272

c4s4 opened this issue Jul 26, 2018 · 6 comments

Comments

@c4s4
Copy link
Contributor

c4s4 commented Jul 26, 2018

Let's consider this code:

map = {"foo": 1, "bar": 2}

println(map["spam"])
if map["spam"] == nil {
	println("is nil")
} else {
	println("is not nil")
}
_, ok = map["spam"]
if ok {
	println("key spam")
} else {
	println("no key spam")
}

This produces following output:

$ anko test.ank 
<nil>
is not nil
no key spam

Which means that:

  • map["spam"] returns a value that is nil but doesn't pass value == nil.
  • Test _, ok = map["spam"] works as expected, telling that map doesn't have key spam.

I think that code map["key"] should throw an error instead than returning a weird nil value.

@MichaelS11
Copy link
Contributor

The not equal to nil is a bug.

package main

import (
	"fmt"
	"log"

	"github.com/mattn/anko/vm"
)

func main() {
	env := vm.NewEnv()

	err := env.Define("println", fmt.Println)
	if err != nil {
		log.Fatalf("Define error: %v\n", err)
	}

	script := `
a = {"b":"b"}

if a.c == nil {
	println("is nil")
}

if a["c"] == nil {
	println("is nil")
} else {
	println("is not nill")
}
`

	_, err = env.Execute(script)
	if err != nil {
		log.Fatalf("Execute error: %v\n", err)
	}
}

I think throwing an error is going to cause more of a headache then it would help. Most of the time just checking for nil will/should work. For the rest of the time, can use ok syntax.

@MichaelS11
Copy link
Contributor

Map not equal to nil fixed here:
#271

@c4s4
Copy link
Contributor Author

c4s4 commented Jul 26, 2018 via email

@mattn
Copy link
Owner

mattn commented Jul 27, 2018

closable?

@MichaelS11
Copy link
Contributor

@mattn ,
Think this can be closed.

@MichaelS11
Copy link
Contributor

Close?

@mattn mattn closed this as completed Aug 15, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants