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

[BUG ?] Variable scope in event handler #28

Closed
d3xMachina opened this issue Sep 4, 2023 · 2 comments
Closed

[BUG ?] Variable scope in event handler #28

d3xMachina opened this issue Sep 4, 2023 · 2 comments

Comments

@d3xMachina
Copy link

d3xMachina commented Sep 4, 2023

In the following example the "handle" value has an ID and unsubscribing works :

local handle = 0

local function _OnStateChange(e)
    if e.ToState == "Running" then
        _P("Handle=")
        _D(handle)
        Ext.Events.GameStateChanged:Unsubscribe(handle)
    end
end

handle = Ext.Events.GameStateChanged:Subscribe(_OnStateChange)

In the following case "null" is displayed :

local handle = Ext.Events.GameStateChanged:Subscribe(function(e)
    if e.ToState == "Running" then
        _P("Handle=")
        _D(handle)
        Ext.Events.GameStateChanged:Unsubscribe(handle)
    end
end)

If this is not a bug and an expected behavior it would be nice to have a way to unsubcribe with something like "Ext.Events.GameStateChanged:Unsubscribe()" without parameter or e.handle when called inside the event handler.

@d3xMachina d3xMachina changed the title [BUG ?] Variable scoping [BUG ?] Variable scope in event handler Sep 4, 2023
@Norbyte
Copy link
Owner

Norbyte commented Sep 5, 2023

Not a bug, this is how the language works: https://www.lua.org/pil/6.1.html
In your second example, local handle is later in the execution order than the closure, and the closure will not capture handle as an upvalue.

Ext.Events.GameStateChanged:Unsubscribe() will not get a version that deletes all subscribers, since it would affect all other mods too and would end up breaking others' code.

@d3xMachina
Copy link
Author

Ok thanks for the explanation, I'm not familiar with lua.

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