Search code examples
pointersluapointer-to-pointer

what is the pointer to pointer equivalent in lua


I know that you can use tables in a similar way to pointers in lua. That being said, what would pointers to pointers look like? Would they look something like dp = {p = {}}? if so what would the equivalent to the c code below be in lua?

void InsertItem(node **head, node *newp){
    node **dp = head;

    while((*dp) && (*dp)->value > newp->value
    {
        dp = &(*dp)->next;
    }

    newp->next = *dp;
    *dp = newp;
}

Solution

  • Yes, double pointer may be translated to Lua as nested table.

    local function InsertItem(head, newitem)
       while head.next and head.next.value > newitem.value do
          head = head.next
       end
       newitem.next = head.next
       head.next = newitem
    end
    
    -- Typical Usage:
    local head = {}
    InsertItem(head, {value = 3.14})
    InsertItem(head, {value = 42})
    InsertItem(head, {value = 1})
    
    -- Now the data is the following:
    -- head  = {next = elem1}
    -- elem1 = {next = elem2, value = 42  }
    -- elem2 = {next = elem3, value = 3.14}
    -- elem3 = {              value = 1   }