Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Is it possible to insert a variable name into a table?

Asked by 6 years ago
local Pets = {}
local Dog = "Woofy."
table.insert(Pets,Dog)

-- Now I can do:
print(Pets.Dog)
-- Output is Woofy.

Is that possible? How?

2 answers

Log in to vote
0
Answered by
Avigant 2374 Moderation Voter Community Moderator
6 years ago

You can use a dictionary for this:

local Pets = {}
Pets.Dog = "Woofy"

print(Pets.Dog)
0
I don't want to do it like that though, because that will basically insert it statically meaning as-is. I want to insert it dynamically like for instance, being able to use scripts to generate variable names and insert into table. Is that possible? Arithmeticity 167 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

Do you mean like this? Here I store random words into the table with myTable[someString] = someString If you're using random words then it'll be hard to use the Dot Operator unless you know what the Key was.

local Pets = {}
math.randomseed(tick())

local function StoreNewPet(pet)
    --Inserting variable name into table. Well not quite.
    --You can't actually put the variable name in the table but you can put a string of what you want the variable name to be
    Pets[pet] = pet
end

local function PrintPets()
    for key,pet in pairs(Pets) do
        print(key .. " is " .. pet)
    end
end

--48 to 122
local function MakeRandomWord()
    local word = ""

    word = string.char(math.random(48,122)) .. string.char(math.random(48,122)) .. string.char(math.random(48,122)) .. string.char(math.random(48,122)) 
    return word
end

StoreNewPet(MakeRandomWord())
StoreNewPet(MakeRandomWord())
StoreNewPet(MakeRandomWord())
StoreNewPet(MakeRandomWord())
StoreNewPet("Fishhhies") --"Fishhhies is Fishhhies"
PrintPets()
print("Dot operator: " .. Pets.Fishhhies) --"Dot operator: Fishhhies"

Answer this question