This topic contains 1 reply, has 2 voices, and was last updated by  Eliot Muir 6 years, 11 months ago.

Table reKey without copy the Table

  • I have line that I use split() to form the table.
    The key to each element is 1, 2 , … etc.
    I would like to use a “name key” to access to the element but I don’t want to copy the table.

    For example:


    After split(“|”)
    1 A
    2 B
    3 C
    4 D

    You can access the element as t[1]

    There is another table that I store the key name that I wanted.

    a 1
    b 2
    c 3
    d 4

    I would like to have auto-complete to show:

    a A
    b B
    c C
    d D

    and not

    1 A
    2 B
    3 C
    4 D

    This will allow me to use a meaningful name for index instead of number.

    I have overwrite the following metamethod: __index, __next, __pairs on the table. Everything is working but not auto complete.

    No way to do it other than making a new table with a helper function something like this:

    function MakeKeyArray(Keys, Values)
       if #Values > #Keys then
          error("Number of values greater than number of keys")
       local R = {}
       for i=1,#Values do
          R[Keys[i]] = Values[i]
       return R

You must be logged in to reply to this topic.