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

Table in a table error?

Asked by 7 years ago
Edited 7 years ago

Alright,

I've made a quick script to add player information such as abc = 0. I'm wondering why this isn't working, can someone guide me on fixing it?

The structure of the table should be;

PLAYERS USERID
    abc = 0
    cba = 123

NOTE: playerProfile, player and checkTable are all defined. They just aren't in the script.

Thanks!

if not checkTable(playerProfile, player.UserId) then -- userId incase they change their name
        table.insert(playerProfile, player.UserId)
        table.insert(playerProfile[player.UserId], {abc = 0, cba = 123}) -- Finds the player in the table(userID)
end

ServerScriptService.GameService:90: bad argument #1 to 'insert' (table expected, got nil) Script 'ServerScriptService.GameService', Line 90

1 answer

Log in to vote
1
Answered by
M39a9am3R 3210 Moderation Voter Community Moderator
7 years ago
Edited 7 years ago

Problem

The error says it all. The first argument to table.insert is always the table that you're trying to add onto. Since you're trying to go into the table and find the index player.UserId, it's assuming the value of it was a table which it is not. You're technically inserting a number value on line 2. When line three goes to look for that index value of the player's Id it does not exist since the index value of the UserId has not been established. Thus it gives you your error.

Confused? Hopefully this helps. Think of the table like so, you used the command table.insert(list, 279), the table is now being read like this:

{ [1] = 279 }

We can keep adding Ids to the list however the index will only go up by one. Realistically, the index value the script thinks you're trying to access is never achieved. So the script is seeing it like this

{
[1] = 279;
[2] = nil;
[3] = nil;
... -etc
}

Solution

table.insert isn't always needed. You can break the bounds of having a regular index and just move to the index yourself. All you have to do is define it and set a value for it.


Final Script

if not checkTable(playerProfile, player.UserId) then -- userId incase they change their name
    playerProfile[player.UserId] = {abc = 0, cba = 123} --Here we are setting the player.UserId as the index value. Whenever you want to get to the table again, you would just need to have the UserId and just do playerProfile[player.UserId]. The line will set the table as the value of the index.
end

Hopefully this answered your question, if you have any more questions feel free to comment below. If you do not quite understand it, I will do my best of further explaining it if you ask what concept you do not get. Do not forget to hit the accept answer button if this did answer your question.
Ad

Answer this question