Assistance with keys in tables "Keys must be strings"

I am creating a cooking game, and currently, when a player joins, a removeEvent fires what’s on each counter to the client that joined the game (these are sent in a format similar to Items = {[Counter][“Item”] = “Tomato”} ).

The problem is, it appears you cannot send mixed tables (non string keys) to the client/server, which I don’t know any alternative to what I am doing, as it is crucial to know what counter the item is on.
Any help?

You have to split the keys and values somehow along these lines:

Items = {
    Keys = {
        Counter,
        etc....
    }
    Values = {
        {"Item" = "Tomato"},
        etc....
    }
}

You can re-convert this to a table with object keys if you want to after it is sent to the client:

tab = {}
for i, key in pairs(Items.Keys) do
    tab[key] = Item.Values[i]
end

Keys must either be all strings or a perfectly sequential numerical array starting at 1 when it is sent through remotes. There is no way around this.

2 Likes

If a counter is empty, and your counters are indexed sequentially starting at index 1, then you can send an empty table instead of sending nothing at all for that counter.

For example, if you have three counters, and counter 2 is empty, then you can do the following:

Items = {
   [1] = {Item = "Tomato"},
   [2] = {},  -- index 2, counter is empty.
   [3] = {Item = "Banana"}
} 

FYI, this is exactly the same table as the following:

-- Keys not explicitly specified while creating a table 
-- => Keys are sequential, starting at 1
-- i.e. we're declaring an array.
Items = {
   {Item = "Tomato"},
   {},  -- index 2, counter is empty.
   {Item = "Banana"}
} 

Alternatively, you can give your counter meaningful ids and avoid the problem altogether.

Items = { 
  IslandCounter = {Item = "Tomato"},
  --KitchenCounter = {}, -- We can omit this safely.
  SinkCounter = {Item = "Banana"}
}
3 Likes

Hmm I guess I’ll name the key :key:Counter and the first index will be the Object of the counter. So then I only have to iterate through the table.