Hello, random people on the internet. I've been trying to find a way to get a value of a variable using a string, how can i search thru a table. Find a variable named something, and take that value? Anything to point me in the right direction?
My modulescript:
local module = {} local toolvalues = { ["Stick"] = 1; ["Bottle"] = 5; } local repstorage = game.ReplicatedStorage function module.Activate(tool) -- "tool" is the string of the name repstorage.Remotes.Gain:FireServer(--[[What can i put in here to find the values, so how can i find the name of a variable in a table, then grab the value?]]) end return module
You use keys. Keys can be almost anything--userdata, strings, numbers, and even booleans. However, you probably shouldn't rely on userdata for a key.
Keys aren't specifically for tables however, they're like fancy dot notation (dot notation being Part.Mesh.Scale).
You can use keys in such a way to index properties of an Instance:
local IN = Instance.new("Part"); IN["BrickColor"] = BrickColor.new("Toothpaste"); IN.Parent = workspace;
Or, you can use keys in a way to index an Instance's children:
local IN = Instance.new("Part"); local NewIN = Instance.new("Part", IN); NewIN.Name = "New Instance"; IN.Parent = workspace; print(IN['New Instance'].Size); --2, 4, 1 (or something like that)
To index a table using a key, you use the square brackets (note, SQUARE brackets, not parenthesis.)
For example:
local Table = {}; local value = "Hello, World!" Table['key'] = value; local MyValue = Table['key'];
local Table = { one = true; two = false; three = "three"; } local OneValue, TwoValue, ThreeValue = Table['one'], Table['two'], Table['three']; print(OneValue, TwoValue, ThreeValue) -->> true, false, three
local Table = { ["Thwack"] = { Damage = 45; Description = "THWACK (nintendo please nerf hero i beg of you)"; }; ["Whack"] = { Damage = 25; Description = "hero doesn't deserve this power" } ["Inside of Party"] = true; }; print(Table.Thwack, Table['Thwack']); -- table 0xMemoryAddress table 0xMemoryAddress print(Table.Whack, Table['Whack']); -- table 0xMemoryAddress table 0xMemoryAddress pcall(function() print(Table.Inside Of Party) --errors end); print(Table["Inside of Party"]); --true
Be sure to look up resources to further develop your knowledge about tables. Tables are a major contender for one of the most useful basic abilities for a language.
Lua-Users: http://lua-users.org/wiki/TablesTutorial
local value = toolvalues[string]