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

Array in closure not updated #21839

Closed
mike-ward opened this issue Jul 10, 2024 · 1 comment
Closed

Array in closure not updated #21839

mike-ward opened this issue Jul 10, 2024 · 1 comment
Labels
Bug This tag is applied to issues which reports bugs.

Comments

@mike-ward
Copy link
Contributor

mike-ward commented Jul 10, 2024

Describe the bug

Maybe I'm misunderstanding something here but I think this test should pass.

Reproduction Steps

fn add(s string, cb fn (string)) {
	cb(s)
}

fn test_add() {
	mut lines := []string{}
	add('msg', fn [mut lines] (s string) {
		lines << s
	})
	assert lines == ['msg']
}

Expected Behavior

lines should equal ['msg']

Current Behavior

lines is empty

Possible Solution

No response

Additional Information/Context

No response

V version

V 0.4.6 65966ae

Environment details (OS name and version, etc.)

V full version: V 0.4.6 8215f21.65966ae
OS: macos, macOS, 14.5, 23F79
Processor: 8 cpus, 64bit, little endian, Apple M2

getwd: /Users/mike/Documents/github/coreutils/src/paste
vexe: /Users/mike/Documents/github/v/v
vexe mtime: 2024-07-10 12:48:46

vroot: OK, value: /Users/mike/Documents/github/v
VMODULES: OK, value: /Users/mike/.vmodules
VTMP: OK, value: /tmp/v_501

Git version: git version 2.45.2
Git vroot status: weekly.2024.27-41-g65966aef
.git/config present: true

CC version: Apple clang version 15.0.0 (clang-1500.3.9.4)
thirdparty/tcc status: thirdparty-macos-arm64 5c1d002f

Note

You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote.
Other reactions and those to comments will not be taken into account.

@mike-ward mike-ward added the Bug This tag is applied to issues which reports bugs. label Jul 10, 2024
@yuyi98
Copy link
Member

yuyi98 commented Jul 11, 2024

Inherited variables are copied when the anonymous function is created. This means that if the original variable is modified after the creation of the function, the modification won't be reflected in the function.
If you need the value to be modified outside the function, use a reference.

mut i := 0
mut ref := &i
print_counter := fn [ref] () {
	println(*ref)
}

print_counter() // 0
i = 10
print_counter() // 10

Don't know the usual way to deal with it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug This tag is applied to issues which reports bugs.
Projects
None yet
Development

No branches or pull requests

2 participants