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

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

Asked by
uhTeddy 101
5 years ago

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

0
What is a custom index to you User#24403 69 — 5y
0
instead of having my index as a number I want to make it a string uhTeddy 101 — 5y
0
No. The table library operates on arrays only. User#24403 69 — 5y
0
You'd have to make your own function and that isn't too hard User#24403 69 — 5y
0
How exactly would I do that? uhTeddy 101 — 5y

1 answer

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

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

Ad

Answer this question