Jump to content

metatables


Antibird

Recommended Posts

Hello there. I never dealt with metatables in LUA scripting, but now I've got a need to track changes in some table that stores some data, so I came up with idea of using metatables ( the '__newindex' event ). I've got acquainted to theory, but my basic test script doesn't work and I gave up trying to find what's wrong to it. I'd be very glad it somebody could guide me for a bit. Thankyou!

test = { x = 1, y = 3, z = 5 }
mt = { __newindex = function( t, key ) outputConsole( "hit" ) end } --This line should output 'hit' in console 3 times after "check" command been used, right?
setmetatable( test, mt )
 
addCommandHandler( "check",
function()
	test.x = 2
	test.y = 4
	test.z = 6
	outputConsole( test.x.." "..test.y.." "..test.z )
end
)

Link to comment

The script is client-side.

__newindex: This method is called whenever we try to create a new key in the table, not look up an existing one.

Yep, my fail, tried to add new field and it worked. Thank you, madis.

Still, basically I need an event that is triggered every time an existing value is changed so I could get the key that stores the value. I used to copy the whole table then periodically compare 'copied' one with 'new' one (that may got some changes in it) key by key. I wonder if there's another way, thought this can be done via metatables.

Link to comment

For synchronization purposes. Saying simply there is a table that stores variables which are changing on clients PC, some are by script, some by user himself; the rate of update is not preset, several values may never change while others are updated 10 times a second. The only syncing function are called by timer periodically. It checks a list of values those should be synced (just another table) key by key and if the value's been changed since the last check, the "key-value" pair is put to the list of data which is eventually sent to other client(s)/server/whatever (the destination).

It all works fine and the only thing I wanted is probably to make the whole procedure more simple and, let's say, more independent of the subject it serves to atm. Not really sure, I like the process of scripting itself ) Got a chance to get into metamethods for a bit I guess.

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...