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

How to read a table in a if-statement?

Asked by
thePyxi 179
7 years ago

So, I'm creating a game in which needs to determine if a string is a type 's' or a type 'm'. I created the tables for S and M but I don't know how to make the if-statement read the table. I've tried to look on the ROBLOX Wiki but nothing seems to make sense or I may have missed something. Can someone give me a link or some advice on how to fix this? Thanks!

local SList = {"Cut the String!",
    "Banana Ninja",
    "Angry Penguins",
    "Full-Life 2",
    "Ice Tower",
    "Morio vs. Dinkey King",
    "Need for Sleep",
    "Pikamon",
    "World of Glue"}

local MList = {"Rocket Team"}

if rp.Selected.Text == #SList then
    recordtype.Value = "s"
elseif rp.Selected.Text == #MList then
    recordtype.Value = "m"
end
print(recordtype.Value.." Here")

1 answer

Log in to vote
1
Answered by
Pyrondon 2089 Game Jam Winner Moderation Voter Community Moderator
7 years ago

There are multiple ways to go about doing this. One way would be to use a table with named indices, or a "dictionary", as some like to call them:

local SList = {
    ["Cut the String!"] = true,
    ["Banana Ninja"] = true,
    ["Angry Penguins"] = true,
    ["Full-Life 2"] = true,
    ["Ice Tower"] = true,
    ["Morio vs. Dinkey King"] = true,
    ["Need for Sleep"] = true,
    ["Pikamon"] = true,
    ["World of Glue"] = true
}

local MList = {["Rocket Team"] = true}

if SList[rp.Selected.Text] then
    recordtype.Value = "s"
elseif MList[rp.Selected.Text] then
    recordtype.Value = "m"
end
print(recordtype.Value.." Here")

If rp.Selected.Text was "Pikamon", for example, it would check SList for "Pikamon". SList['Pikamon'] is true, so the result of the condition would be true.


Although the above method is preferable, another way to achieve this would be to loop through the table and see if the value is present:

local SList = {
    "Cut the String!",
    "Banana Ninja",
    "Angry Penguins",
    "Full-Life 2",
    "Ice Tower",
    "Morio vs. Dinkey King",
    "Need for Sleep",
    "Pikamon",
    "World of Glue"
}

local MList = {"Rocket Team"}
local function isIn(t, s) --// Create a function to check if value `s` is in table `t`.
    for _, v in next, t do
        if v == s then return true end; --// If the value is present, return `true`.
    end;
    return false; --// If it wasn't found, return `false`.
end;

if isIn(SList, rp.Selected.Text) then
    recordtype.Value = "s"
elseif isIn(MList, rp.Selected.Text) then
    recordtype.Value = "m"
end
print(recordtype.Value.." Here")

Read more about: For loops, functions, and tables.

Hope this helped.

Ad

Answer this question