1

I'm writing a script in lua, what i need to do is run a piece of code every time a variable is set.

The code i have is:

plane = {}
plane.status = "foo"
plane.status = "bar"

I want to run this every time a value is assigned to a variable in plane

print "status=" + <value>

How would i go about this? i've head it has something to do with __newindex.

1 Answer 1

3

Yes, you set a proxy table for plane and set a __newindex metamethod for it.

function managed(t,f)
        return setmetatable({},{__index=t, __newindex=f})
end

plane = managed({},print)
plane.status = "foo"
plane.status = "bar"

In practice, in the __newindex metamethod, you'll set the values in the original table using rawset.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that __newindex is called only when the key is not present the table. If you want to be able to store the value and also still intercept the calls, you have to store the values in another table, not in the managed table.
@MichalKottman, of course. I meant by managed the original table. I've edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.