I want to make 1 function that sets the value to what it is supposed to be and it also fires a remoteEvent (script.remoteEvent) and an event (script.event)
The thing is, I dont know how to do that, and what ive tried doesnt work
i assume u are using a module script
its simple to make a function that change the value of a table in a module script
u could first make the function, then to set a value just
get the tables value like for example Table.selectedvalue, then do what u want with it, u could also pass those values using a remote event if thats what u wanna do.
example:
local module = {
a = 1,
b = 2,
c = true
}
function module.new()
local remoteEvent = script:WaitForChild("RemoteEvent")
module.a += 1 -- setting a value
print(module.a)
remoteEvent:FireServer(module.a, module.b, module.c) -- fire remote event
end
return module
[quote=“Vex, post:1, topic:3078048, full:true, username:kittykitkat_0510”]
Lets say I have a table
-- Assuming you have a RemoteEvent and an Event defined somewhere in your script
local remoteEvent = script.remoteEvent
local event = script.event
-- Define your module table
local module = {
gems = 1,
gold = 20,
Ownedpets = {
dog = {
multiplier = 999
}
}
}
-- Function to set a nested value in the module table
local function setNestedValue(tbl, keyPath, value)
local keys = keyPath:split(".")
local current = tbl
for i = 1, #keys - 1 do
current = current[keys[i]]
end
current[keys[#keys]] = value
end
-- Function to set a value in the module table and fire both events
local function setValueAndFireEvents(keyPath, value)
if keyPath:find("%.") then
setNestedValue(module, keyPath, value)
else
module[keyPath] = value
end
-- Fire the RemoteEvent
remoteEvent:FireServer(keyPath, value)
-- Fire the Event
event:Fire(keyPath, value)
end
-- Example usage
setValueAndFireEvents("gems", 10)
setValueAndFireEvents("Ownedpets.dog.multiplier", 1000)
Try to use the __newindex metamethod for tables, this will call the function whenever its trying to set the value of a field.
Fires when table[index] tries to be set (table[index] = value), if table[index] is nil. Can also be set to a table, in which case that table will be indexed.
This is another good way to handle this and was my first thought. My main concern would be that, metatables are shallow to the table they are attached to. This means, to update nested tables you need to implement a recursive solution. Nonetheless, for simple nested table structures this would be fine.
I will note, metatables have a large memory footprint and they are slow and clunky. If you use metatables it is wise to use them in rare instances where they are deemed a must.