简体   繁体   中英

Passing a function as a variable and assigning it to an object still able to reference “self” in Lua

So, I'm trying to write a function which accepts functions as its parameters and sets them as 'object' methods in Lua. Is there a specific syntax for this of which I'm not aware?

local function createObjectWithMethods(method1, method2)
    local object = {}
    object.meth1 = method1
    object:meth2 = method2 --this throws an error expecting parameters
    return object
end

Is there another way to go about this? I know that I could hardcode a method for the object, but this code needs to have functions passed as parameters, and some of those functions need to be able to reference self. Any ideas?

You need to write the passed-in methods without the automagic self syntax sugar.

That is you can't use:

function obj:meth1(arg1, arg2)
    -- code that uses self
end

(unless these functions are defined on some other object and being cross-applied to the new object).

Instead you need to write what the above is sugar for yourself.

function meth1(self, arg1, arg2)
    -- code that uses self
end
function meth2(self, arg1, arg2)
    -- code that uses self
end

Then you can just call the function normally and assign the functions normally.

local function createObjectWithMethods(method1, method2)
    local object = {}
    object.meth1 = method1
    object.meth2 = method2
    return object
end

createObjectWithMethods(meth1, meth2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM