How to pass by reference from one script to the other in Lua?

Lets say I have a script with the following:

OD = {}

function OD:new(o)
    o = o or {}
    self.__index = self
    setmetatable(o, self)
    return o
end

function OD:DummyFunction()
    print("Dummy function")
end

exports('GetOD', function()
    return OD:new()
end)

Citizen.CreateThread(function()
    print(OD) -- table: 00000000D1719CF0 / correct
    print(OD.DummyFunction) -- function: 000000011FC48840 / correct

    od1 = OD:new()
    print(od1) -- table: 00000000D16FEEB0
    print(od1.DummyFunction) -- function: 000000011FC48840 / correct

    od2 = exports["od-framework"]:GetOD()
    print(od2) -- table: 00000000D1701DF0 / correct
    print(od2.DummyFunction) -- nil / but what I want it to be is 'function: 000000011FC48840'
end)

What I want is to call the export ‘GetOD’ to get a new object of OD but the references to the functions need to be the same as the original OD. When I now call the export ‘GetOD’ the ‘DummyFunction’ is nil instead of ’ function: 000000011FC48840’.

I know I can just return OD like this:

exports('GetOD', function()
    return OD
end)

but the reference to the DummyFunction will be different and I want it to be the same reference. Any solutions to make this work?

1 Like

You need to add the function in exports {} in the fxmanifest.lua

Let me rephrase my question: What I want to do is to make instances of a class and pass those instances to other scripts through a export or event.
I am able to make instances of a class as I displayed above with ‘od1’ but when I try create a instance inside of a export and return that instance it doesn’t seem to work. I edited the code snippet from above to make the issue maybe a bit more clear:

OD = {}

function OD:new(o)
    o = o or {}
    self.__index = self
    setmetatable(o, self)
    return o
end

function OD:DummyFunction()
    print("Dummy function")
end

exports('GetOD', function()
    local odTest = OD:new()
    print(odTest.DummyFunction) -- function: 000000011FC48840 / correct
    return odTest
end)

Citizen.CreateThread(function()
    print(OD) -- table: 00000000D1719CF0 / correct
    print(OD.DummyFunction) -- function: 000000011FC48840 / correct

    od1 = OD:new()
    print(od1) -- table: 00000000D16FEEB0 / correct
    print(od1.DummyFunction) -- function: 000000011FC48840 / correct

    od2 = exports["od-framework"]:GetOD()
    print(od2) -- table: 00000000D1701DF0 / correct
    print(od2.DummyFunction) -- nil / but what I want it to be is 'function: 000000011FC48840'
end)
1 Like

The thing is that exports and events seem to be capable of only returning by value instead of by reference but I want to return by reference between scripts, how?

1 Like

Any solution?