Hey All,
I have a long script in ServiceScriptService that handles the calling and saving of player data. There is a lengthy function in the script that exceeds the 200 local variables allowed to be present a function. I need to find a way around this 200 local variable limitation.
Here is an example of the function with 200+ local variables:
function onPlayerEntered(player)
-- Setup the keys for data storage
local initKey = "user_" .. player.UserId .. "_init"
local moneyKey = "user_" .. player.UserId .. "_money"
local invenValKey = "user_" .. player.UserId .. "_invenVal"
local invenCountKey = "user_" .. player.UserId .. "_invenCount"
-- Another 50 of these types of local variables
-- If player does not have values or if debug mode is on, set the default values
if (datastore:GetAsync(initKey) == nil or debugMode == true) then
datastore:SetAsync(initKey, true)
datastore:SetAsync(moneyKey, 0)
datastore:SetAsync(invenValKey, 0)
datastore:SetAsync(invenCountKey, 0)
-- Another 50 of these types of local variables
end
-- Set the variables from datastore if player already has values
local init = datastore:GetAsync(initKey)
local money = datastore:GetAsync(moneyKey)
local invenVal = datastore:GetAsync(invenValKey)
local invenCount = datastore:GetAsync(invenCountKey)
-- Another 50 of these types of local variables
-- Setup the stats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local moneyCount = Instance.new("IntValue")
moneyCount.Name = "Money"
moneyCount.Value = money
moneyCount.Parent = leaderstats
local value = Instance.new("IntValue")
value.Name = "InventoryValue"
value.Value = invenVal
value.Parent = player
local count = Instance.new("IntValue")
count.Name = "InventoryCount"
count.Value = invenCount
count.Parent = player
-- Another 50 of these types of local variables
end
I tried to decrease the local variable count by placing a group of local variables into a table. I would then reference those items in the table like this:
local dataTable = {
init = datastore:GetAsync(initKey), -- Previously local variables
money = datastore:GetAsync(moneyKey),
invenVal = datastore:GetAsync(invenValKey),
invenCount = datastore:GetAsync(invenCountKey),
-- Reapeat for the other 50
}
-- Reference the above table items in stats
local moneyCount = Instance.new("IntValue")
moneyCount.Name = "Money"
moneyCount.Value = dataTable[money] -- BUT money is underlined RED and not recognized
moneyCount.Parent = leaderstats
-- And so forth with the other stats
When referencing the dataTable[money], money is underlined in RED and studio doesn’t recognize it- Unkown global ‘money’
Any suggestions on what I’m doing wrong or a better approach to decreasing the local variable count?