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

Spurious nil table keys during iteration #93

Open
TheCount opened this issue Jan 7, 2023 · 2 comments
Open

Spurious nil table keys during iteration #93

TheCount opened this issue Jan 7, 2023 · 2 comments

Comments

@TheCount
Copy link
Contributor

TheCount commented Jan 7, 2023

When iterating over a runtime.Table using the Next() method, I occasionally get a nil key return value with ok == true.

I can try putting together a minimal example of the bug, however, looking at the source code, I see this:

return NilValue, NilValue, true

This looks like it should be return NilValue, NilValue, false instead in the first if. Could this already be the fix?

@arnodel
Copy link
Owner

arnodel commented Jan 8, 2023

It is possible to get a nil key return value and for ok to be true. The returned value ok is true if the key passed in to Next is valid (i.e. is present in the table), but if it is the last key in the table then then there is no next key - value so what is returned is NilValue, NilValue, true (this is what happens in the line you refer to).

For example if a table t has one item in it with key = "hello" and value = 42 then

  • calling t.Next(nil) returns "hello", 42, true
  • calling t.Next("hello") returns nil, nil, true

(syntax above is not quite correct because I should write rt.NilValue instead of nil, etc)

If you encounter another type of situation then please give me an example so that I can understand and fix the issue.

@TheCount
Copy link
Contributor Author

TheCount commented Jan 8, 2023

Aah, thank you for this explanation, that makes a lot of sense.

The thing that threw me off is that often in Go, a bool return value like this indicates whether there is another entry.

I'd like to suggest to extend the documentation of Table.Next a bit to make all of this clearer, maybe something like the following?

// Next returns the key-value pair that comes after k in the table t.
// If k is NilValue, the first key-value pair in the table t is returned.
// If k is the last key in the table t, a pair of NilValues is returned.
// If the table t is empty, the returned key-value pair is always a pair of NilValues, regardless of k.
// In all cases, ok is true if and only if k is either NilValue or a key present in the table t.

Thanks again!

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

2 participants