Search code examples
stringvariablesluatype-conversionroblox

How can I use a parameter to alter which data my profile.Data is accessing?


local expType = tostring(type1)
        local expTypeStat = expType:gsub("Exp", "")
        local profileDataExpType = "profile.Data."..expType

Here I want to change which data is pulled from profile.Data depending on which expType is given to the function I'm making.

For an example, type1 would be something like StrengthExp. But when adding strength, I want to reference the Strength stat itself in the same function, so I used the gsub function to remove the Exp from StrengthExp.

To access the player's stats and exp amounts, I need to use profile.Data.Strength or profile.Data.StrengthExp for example.

if profileDataExpType <= math.round(100 * (expTypeStat / 2)) then

Here is the part of the function that I want to use the profileDataExpType and expTypeStat variables as code instead of strings.

Is there a different way to access the right profile.Data depending on what expType is given to the function? Or is there a way to convert that string into code? I couldn't find anything online or in the documentation

I tried writing the code like this, replacing the actual name of the data with expType:

if profile.Data.expType <= math.round(100 * (profile.Data.expType/ 2)) then

I tried this before converting expType to a string thinking it would use the parameter expType instead of looking for data called "expType" within profile.Data


Solution

  • I managed to workaround the issue by using the rawget global. Here's how I assigned the variables I needed:

    local expType = tostring(xpType)
    local expTypeStat = expType:gsub("Exp", "")
    local profileDataExpType = rawget(profile.Data, expTypeStat)
    local profileDataExp = rawget(profile.Data, expType)
    

    rawget gets the value of the profile.Data table and returns the value of the index you give it, in this case expTypeStat and expType.

    If you then want to change the value, you can use the rawset global. Here's an example:

    rawset(profile.Data, expType, (0 + leftoverExp))