Dear pro scripters,
So can someone explain to me the whole state thing. Wikipedia
The way I understand it right now, state is just value(s) that change. Many times I want different modules to access “shared state” I simply make a module with a return table with the state, then anyone can freely read it and change it.
What’s my question?
My question originates from the fact that I keep wanting to have some functionality when a state changes. For example my problem right now is I have a module on the client called “Settings” and any module on the client can access a “setting” by doing Settings.get()
. What’s a setting anyway? Settings are anything on the client that is client-only and is only sent to the server to store in datastore. Examples are UI preferences, other preferences, UI layout. I want to be able to change a “setting” table and the changes automatically get sent to the server to be saved. I can’t just do settings.key = value
because that will not run any code to update the server. Now maybe there’s a much better way of doing this (please let me kow)
There’s 2 ways I know of to run a function when a key in a table changes.
-
Make an object with a “Data” field and a “SetValue” method, and read values by doing
Data.NestedTable.Key
and write values by doingObject:SetValue("NestedTable.Key")
, then you have to remember to not directly set the table and always go through the set method and it’s also annoying to pass the entire path into set method. This is what ReplicaService uses. -
Use proxy tables. You can use “proxy tables” using newproxy() or just having a blank table. Then you can use the __index and __newindex metamethod to track when a key changes. If you set a
proxy[key] = {}
you will then have to make another proxy table for the nested table and so on. This has some complications like you can’t use the table library or loop through the proxy table normally, and they are much much slower to create, read, and write to then normal tables.
Both of these methods feel hacky, so I want to know what to the pro scripters do?
I think I might be looking at the whole thing the wrong way and “good code” would not run into this problem anyway (if so then what’s the proper way?)
Okay thanks for reading and maybe answering