sodiseng
sodiseng

Reputation: 23

Lua - set table(anonymous) value

return{
    initime = 1;
    isneed= true;          -- need to modify
    testfn=function()
        isneed = false;    ---how to modify the "isneed" value?
    end
}

i wanna modify the isneed's value,i have try like this

local testdata;
testdata={
    initime = 1;
    isneed= true;
    testfn=function()
        testdata.isneed = false;
    end
}

return testdata;

but the code that i dont want,i think have another way to set the value.

Upvotes: 1

Views: 132

Answers (1)

Personage
Personage

Reputation: 484

Building on @luther's comment, the code you have in your second example should work.

local testdata = {
    initime = 1,
    isneed = true,
    testfn = function()
        testdata.isneed = false
        return
    end
}

print(testdata.isneed)
testdata.testfn()
print(test.data.isneed)

This should output the following:

true
false

Alternatively, if you wanted to get a little fancier, you could use a metatable to overload the call operator for your table testdata:

local testdata = {
    initime = 1,
    isneed = true,
    testfn = function()
        testdata.isneed = false
        return
    end
}

testdata = setmetatable(testdata, {
    __call = function(self)
        return self.testfn()
    end
})

print(testdata.isneed)
testdata()
print(testdata.isneed)

This example's output is equivalent to the above output. Depending on what exactly you wish to accomplish with your code, overloading the call operator with a metatable could offer you some more flexibility. Using this approach, you could change your code slightly like this, making use of the self parameter in the __call function:

local testdata = setmetatable({initime = 1, isneed = true}, {
    __call = function(self)
        self.isneed = false
        return
    end
})

print(testdata.isneed)
testdata()
print(testdata.isneed)

This will produce the same output as the first example.

Upvotes: 1

Related Questions