macroland
macroland

Reputation: 1025

Lua userdata pass by reference - local functions in different files

I have 2 Lua files, namely mydialog.lua and rangecontrol.lua. The code in mydialog.lua is as follows:

local function mydialog()
    --omitted
    local wb_responses=activeobj() --wb_responses points to the current activeobj(), say Obj1
    UI.m_txt=sys.rangetextcontrol(UI.sbSizerInput:GetStaticBox() ,wb_responses) --wb_responses is passed by reference
    --Selection event happened
    --Omitted
    --If clicked on a checkbox execute the following line
    print(wb_responses) --Still prints Obj1 instead of Obj2
end
sys.tools.mydialog=mydialog

Code in rangecontrol.lua:

local function rangetextcontrol(parent, wb_txtBox) 

    local  m_txtBox=nil
    m_txtBox=wx.wxTextCtrl( parent, wx.wxID_ANY, "", wx.wxDefaultPosition, wx.wxDefaultSize, 0 )

    local function GetRange()
        wb_txtBox=activeobj()
        local ws=activeobj():cur()
        local rng=ws:selection()
        if (rng==nil)  then return end
        m_txtBox:SetValue(rng:tostring()) -- Here wb_txtBox correctly refers to Obj2
    end

    m_txtBox:Connect( wx.wxEVT_LEFT_DOWN, function(event)
        wb_txtBox=activeobj() --Current activeobj() changed, say Obj2
        local ws=wb_txtBox:cur()
        ws:connect(GetRange) --There is a selection event, call GetRange

        event:Skip()
    end)
    return m_txtBox
end
sys.rangetextcontrol=rangetextcontrol

Briefly what happens:

1) A dialog starts and it has a textcontrol (there might be several textcontrols)

2) When user makes a selection from an object, the text box is populated.

3) My goal is to track from which object the selection is made.

My confusion: Although I pass wb_responses a userdata type, which should be passing by reference to the rangetextcontrol which keeps track of the selections, it seems that wb_responses never changes since it always prints info on Obj1. Therefore, I assume it always points to the first object that it has been initialized with in mydialog.lua. What could I be doing/thinking wrong?

Upvotes: 1

Views: 134

Answers (1)

Piglet
Piglet

Reputation: 28950

local function mydialog()
    --omitted
    local wb_responses=activeobj() --wb_responses points to the current activeobj(), say Obj1
    UI.m_txt=sys.rangetextcontrol(UI.sbSizerInput:GetStaticBox() ,wb_responses) --wb_responses is passed by reference
    --Selection event happened
    print(wb_responses) --Still prints Obj1 instead of Obj2
end

You print wbresponses right after you initialize it. How should it change its value? There won't be any event handling between those two lines of code.

Upvotes: 0

Related Questions