Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Is it possible to use table.insert() with a custom index?

I am working on a table where I need to make a custom index, how exactly would I be able to do this?

5 comments

0

What is a custom index to you

0

instead of having my index as a number I want to make it a string

0

No. The table library operates on arrays only.

0

You'd have to make your own function and that isn't too hard

0

How exactly would I do that?

1 answer

✓ Accepted answer

The table library currently does not operate on dictionaries. Now, more along the lines of the spirit of your enquiry, you can use this function:

local function setKeyAndValue(t, k, v)
    t[k] = v
end

local tbl = {}
setKeyAndValue(tbl, "Key", 2)
print(tbl.Key)

Which just sets the key and values. Pretty self explanatory.

#Fun fact

With table.insert(list, pos, value) you can set value to be at position pos. insert shifts the indices to the right by 1 if the index is not nil.

##Examples

local tbl = {"hello", "world", "yes", "no"}

table.insert(tbl, 1, "goodbye")
print(table.concat(tbl, ", "))
--> goodbye, hello, world, yes, no

goodbye is placed at index 1, and hello, formerly index 1, is shifted down so is everything else.


####Don't forget to accept if this helps

This discussion is preserved as it was. New answers, comments, and votes are closed.