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

Finding if a value is a table or a number?

Asked by 6 years ago

I am trying to loop through a dictionary of player stats, but am having trouble finding a way to make sure a value is a table vs a number value.

My Code:

01     Players[player]["Stats"] = {
02        Chest = {Pectorals = 1},
03        Arms = {Biceps = 1, Triceps = 1},
04        Legs = {Quads = 1, Glutes = 1, Hamstring = 1, Adductors = 1},
05        Core = {Abs = 1, LowerBack = 1},
06 
07    }
08    Players[player]["Stats"]["Stats"] = Instance.new("Folder",player)
09 
10    StatChangeEvent.OnServerEvent:Connect(function(plr)
11        local output = 0
12        local function loop()
13            for i,v in pairs(Players[plr]["Stats"]) do
14                if v[1] then
15                    loop(v)
View all 29 lines...
0
You can use type(variable) == "number" to check if it is a number or not. Using tonumber(variable) could cause false positives where a string could be considered a number value, which could be exploited and cause bugs. Overscores 381 — 6y

2 answers

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

You can use the tonumber function to see if something is a number or not. If something can be converted into a number, it returns that number, otherwise, it returns nil.

1local t1 =  {Jeff = "gee",gdhg = "ooga nooba"}
2local t2 = {"hey",122}
3 
4print(tonumber(t1))--nil
5print(tonumber(t2))--nil
6print(tonumber(1))--1
7print(tonumber("1"))--1

you could also use the type function to see if the type of an object is a table/number

1local t1 =  {Jeff = "gee",gdhg = "ooga nooba"}
2local t2 = {"hey",122}
3 
4print(type(t1))--table
5print(type(25532))--number

Addition:

If you want to see if something like a string contains a number like:

"happy 57th birthday!"

you would have to use the match function of the strings library to get it

1local str = "happy 57th birthday"
2 
3print(str:match("%d+"))--57

(%d+ gets 1 or more repetitions of digits)

0
Good stuff DinozCreates 1070 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

I'm assuming you mean this?

01     Players[player]["Stats"] = {
02        Chest = {Pectorals = 1},
03        Arms = {Biceps = 1, Triceps = 1},
04        Legs = {Quads = 1, Glutes = 1, Hamstring = 1, Adductors = 1},
05        Core = {Abs = 1, LowerBack = 1},
06 
07    }
08    Players[player]["Stats"]["Stats"] = Instance.new("Folder",player)
09 
10    StatChangeEvent.OnServerEvent:Connect(function(plr)
11        local output = 0
12        local function loop()
13            for i,v in pairs(Players[plr]["Stats"]) do
14                if v[1] then
15                    loop(v)
View all 32 lines...
0
that doesn't work, you have to use tonumber() DeceptiveCaster 3761 — 6y

Answer this question